Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript function gives expected result in the console, but unable to assign result to a variable

I’m unable to assign the result of a function call to a variable.

Let’s start with the following object:

let employees = [
    {
    id : 1,
    name : 'John Smith',
    age : 48,
    salary : 100000
    },

    {
    id : 2,
    name : 'Mary Jones',
    age : 29,
    salary : 78000,
    },

    {
    id : 3,
    name : 'Philip Lee',
    age : 36,
    salary : 160000,
    }
]

I have a function that accesses each employee’s salary (except Mary) and applies a 20% increase:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function applySalaryIncrease(employees) {
    for (let i=0; i < employees.length; i++) {
        if (i == 1){
            continue;
        }
        employees[i].salary = employees[i].salary * 1.2;
    }
 }

Next, I submit the following in the console:

applySalaryIncrease(employees)
employees

And, I see in the console that the salaries for John and Philip have increased, as expected.

However, when I assign the result to a variable named updatedEmployees, the result in the console is undefined.

updatedEmployees = applySalaryIncrease(employees)

enter image description here

Why is this happening?

Thanks! (JavaScript rookie here)

>Solution :

Your function isn’t returning anything explicitly, so it returns what JavaScript functions without an explicit return value deliver, which is undefined.

Fix it:

function applySalaryIncrease(employees) {
    for (let i=0; i < employees.length; i++) {
        if (i == 1){
            continue;
        }
        employees[i].salary = employees[i].salary * 1.2;
    }
    return employees; // <-- explicitly return employees here
}

Usually it’s not the best idea to mutate function arguments, so as long as all the array objects simply hold primitive data types, it’s usually preferrable to create a shallow copy of the array passed:

function applySalaryIncrease(emps) {
    const employees = [...emps]; // this avoids mutating the array passed to the function
    for (let i=0; i < employees.length; i++) {
        if (i == 1){
            continue;
        }
        employees[i].salary *= 1.2;
    }
    return employees; // <-- explicitly return employees here
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading