Forem

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.


Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay