Home > OS >  Rest operator with Variable reference
Rest operator with Variable reference

Time:07-30

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?

CodePudding user response:

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

CodePudding user response:

In the second example array looks like this: [4] instead of [1, 2, 3, 4].

There are not tuples in JavaScript, you can't wrap items with () you have to use [].

Also, your function expect each item separately, so you should spread first

const myValues = [1, 2, 3, 4]
sum(...myValues)

CodePudding user response:

when you write let total = sum(1, 2, 3, 4) this means passing 4 arguments to function so it is passe 4 values and sum it to 10. but in this case, let my values = (1, 2, 3, 4) you are redefied my values four times to 4 only so when the final function will execute it will just have one value 4 for sum . so the final output is 4.

  • Related