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.


SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️