Home > Software design >  JavaScript function gives expected result in the console, but unable to assign result to a variable
JavaScript function gives expected result in the console, but unable to assign result to a variable

Time:09-12

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:

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)

CodePudding user response:

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
}

CodePudding user response:

You are not returning any values so your variable gets undefined as a return from the function. However if you add a return employees before closing your function and after your loop it will return it.

Edit: I just saw it but it is exactly like the guy above me said

  • Related