Hi guys! When I was working on my JS Arguments Optional Problem, I encountered this weird behavior of arguments object. Please see the code below:
function add1() {
//put arguments passed in an array
let args = Array.from(arguments);
let sum = x => y => x+y;
return sum(args);
}
let add2 = x => y => x+y;
add1(2)(2); //returns '22'
add2(2)(2); //returns 4
I am aware that parseInt() would fix this, but I would like to know what causes the arguments in add1() turn into strings?
It’d be great if someone could provide an explanation to this behavior.
The first argument of your sum() is an array [2]. The second argument is 2.
Adding them results the expression ([2] + 2).
Even though it doesn’t make any sense to add them, Javascript will try to add them by coercing array to string, which results ([2].toString() + 2).
Hence, your final output is '22'
So, trying to resolve this by calling parseInt() is a bad idea.