This snippet of JavaScript code alerts 1 as answer. Can anyone please explain how this code executes?
const b = [1,2,3];
const f = (a, ...b) => a+b;
alert( f( 1 ) );
This snippet of JavaScript code alerts 1 as answer. Can anyone please explain how this code executes?
const b = [1,2,3];
const f = (a, ...b) => a+b;
alert( f( 1 ) );
 
    
     
    
    There are a couple of things going on here. The main one is that you're shadowing b, so the b outside the function isn't used within it. Instead, within it, you're creating a new array (because you've used a rest parameter, ...b) and assigning it to the b parameter. Since you call f with just one parameter, that array is empty. 1+[] is "1" because when either of the operands to + isn't a primitive (arrays aren't primitives), it's coerced to a primitive, and coercing an array to a primitive (indirectly) results in doing a .join(",") on the array. With a blank array, .join(",") is "". Then, since one of the operands is a string, the other operand (1) is coerced to string ("1") and it does "1"+"" which is, of course, "1". (Details on that last bit in the spec.)
 
    
    f(1) is the same as 1 + []
f(1,2,3) is the same as 1 + [2, 3]
That's all...
The first line const b = [1,2,3]; is not used because the b in the lambda expression is the argument, not the constant declared before.
 
    
    You can reference variables in a function call, however, when you define a function expression, the parameters name do not refer to any variables.
You'll get the expected result if you call the function like this:
alert(f(1, b));
 
    
    It takes the rest parameters ... as an array b.
While this is empty, it is converted to an empty string and both operands are treated as string, because if one is a string, then it adds all values as string.
The result is '1'.
const b = [1, 2, 3];
const f = (a, ...b) => a + '';
console.log(typeof f(1)); 
    
    Reproducing this in my browser's development tools console looks like this:
> b = [1,2,3]
> f = (a, ...b) => a+b
> f(1)
< "1"
// so it results in the string 1, why's that?
// lets try logging what a and b are in the function
> g = (a, ...b) => console.log("a=%o, b=%o", a, b)
> g(1)
< a=1, b=[]
// ah, so b is an array, which is what the spread operator does 
// (gathers all remaining arguments into an array, so the question 
// is then what does JavaScript return for the number 1 added to an empty array?
> 1 + []
< "1"
This behavior is one of the many quirks of JavaScript when using the + operator on different types.
