DEV Community

Adrian Skar
Adrian Skar

Posted on

+ operator coerces functions into strings

TIL (Today I Learned) that the addition operator coerces functions into strings.

Advice: Be careful when using currying and the + operator.


I was reviewing the currying concept from this FreeCodeCamp's exercise and tried to play a bit with the outputs when noticed this:

function add(x) {
    return y => z => x + y + z;
}
console.log(add(3)(2)); // Function 
console.log(add(3)(2)(1)); //  6 
console.log(add(3)(add(2))(1)); // 3y => z => x + y + z1 ???
console.log(typeof add(3)(add(2))(1)); // string
Enter fullscreen mode Exit fullscreen mode

I thought it should return a function or an error and tested running it on the browser and with different tools but I got the same result 3y => z => x + y + z1.

I even asked GPT, Phind and Perplexity AI's but they, as eloquent as they can be sometimes, said that it was not possible and the correct number or an error should be returned.

Sometimes you just have to get to the docs and back to basics.
Whenever the + operator finds a string or a non numeric value it'll concatenate all values as strings instead of summing them.

So the breakdown of calling add(3)(add(2))(1) would be:

x = 3 // Number
y = "y => z => x + y + z" // String
z = 1 // Number
Enter fullscreen mode Exit fullscreen mode

And everything gets concatenated as one of the operands is of String type.


Top comments (0)