简体   繁体   中英

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:

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)

在此处输入图像描述

Why is this happening?

Thanks! (JavaScript rookie here)

Your function isn't return ing 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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM