Skip to content
Advertisement

Rest operator with Variable reference

I can’t understand why these two codes don’t work the same:

function sum(...array) {
return array.reduce((total, element) => {
    return total += element;
})};

let total = sum(1, 2, 3, 4);
console.log(total);

This one works as expected and returns the sum of …array (10)

But when I try to do the same by calling the function with a variable reference:

function sum(...array) {
return array.reduce((total, element) => {
    return total += element;
})
}

let myValues = (1, 2, 3, 4)

let total = sum(myValues);
console.log(total)

The output is 4. Why the function works differently in the two situations?

Advertisement

Answer

Parenthesis are expressions that JS evaluates. Similar to how:

let a = (1 + 2) // a = 3 

let b = (10 || 5) + 1 // b = 11. 10 is truthy so (10 || 5) evaluates to 10

let c = (null || 6) + 1 // c = 7. (null || 6) evaluates to 6 

In this case, (1,2,3,4) evaluates to 4. If you want to use variables, you can add the numbers to an array and spread ... that array when calling the function:

function sum(...array) {
return array.reduce((total, element) => {
    return total += element;
})
}

let myValues = [1, 2, 3, 4]

let total = sum(...myValues);
console.log(total) // 10
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement