I can’t understand why these two codes don’t work the same:
JavaScript
x
8
1
function sum(array) {
2
return array.reduce((total, element) => {
3
return total += element;
4
})};
5
6
let total = sum(1, 2, 3, 4);
7
console.log(total);
8
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:
JavaScript
1
11
11
1
function sum(array) {
2
return array.reduce((total, element) => {
3
return total += element;
4
})
5
}
6
7
let myValues = (1, 2, 3, 4)
8
9
let total = sum(myValues);
10
console.log(total)
11
The output is 4. Why the function works differently in the two situations?
Advertisement
Answer
Parenthesis are expressions that JS evaluates. Similar to how:
JavaScript
1
6
1
let a = (1 + 2) // a = 3
2
3
let b = (10 || 5) + 1 // b = 11. 10 is truthy so (10 || 5) evaluates to 10
4
5
let c = (null || 6) + 1 // c = 7. (null || 6) evaluates to 6
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:
JavaScript
1
10
10
1
function sum(array) {
2
return array.reduce((total, element) => {
3
return total += element;
4
})
5
}
6
7
let myValues = [1, 2, 3, 4]
8
9
let total = sum(myValues);
10
console.log(total) // 10