Skip to content
Advertisement

Rest operator with Variable reference

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

JavaScript

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

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

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement