QUESTION: Arguments Object behavior in a Currying Fn

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.

@gunhoo93 Thanks! Your explanation made sense to me. I ended up using sum(args[0]) instead to avoid using parseInt().

Why do you even need args?

I got curious and tried to play with the inputs. I used args so I could also use the function to solve add1(1,2,3) as well.

But given your implementation, add1(1, 2, 3) is impossible.

My bad for not including it in the snippet as I just wanted to focus my question on this particular part of my code which you’ve had answered already.

So thanks again and happy coding! :slight_smile: