The Curious case of Addition(+) operator in JavaScript — Nuts and Bolts Series

laxmena
2 min readOct 17, 2023

--

Photo by Joan Gamell on Unsplash

Here’s a quiz, what would be the result of the following expression:

var result = null + true + “hello”;

At first glance, any sane Software engineer would think compiler would throw an error.

But this is JavaScript, and JS has its own quirkiness. JS not only does not throw an error for this expression, it also successfully evaluates and returns a response.

This sparked my curiosity, and I started looking deep into it. As I call it — go till the Nuts and Bolts of things. Lets dive deep!

Something to note:

In JavaScript, The (+) operator is overloaded for two distinct operations:

  1. Adds two numbers
  2. Concatenates two strings

How does JS evlautes expressions with Addition(+) operator:

When JS engine recognizes an expression with (+) operator, it first boils down the operands to its primitive types. More on JS primitives in the next post :)

Then the following rules are used to evaluate the final result:

  1. If any one operand is a string, other operands are converted to strings. then string concatenation is performed.
  2. BigInt value can only be added with another BigInt. When used with other types, TypeError is thrown.
  3. Otherwise both operands are converted into numbers.

Walking through step by step evaluation of the expression:

Heres the expression again:

var result = null + true + “hello”;

Step 1: null + true

  • Both operands are already in their primitive type.
  • They are not string or BigInt.
  • So as per rule 3, operand’s are converted to numbers.
  • Number(null) + Number(true) => 0 + 1 => 1

Note: Number(null), Number(false) resolve to 0.

Step 2: 1 + “hello”

  • One of the operand is a string. So other operand is converted to string using the toString() method.
  • String concatenation is performed on the two strings.
  • (1).toString() + “hello” => “1” + “hello” => “1hello”

So the final result of the expression is: 1hello

Interesting isn’t it? Let me know your thoughts, and if you have faced these scenarios before, but have skipped past this!

Just for fun, I would recommend you to try and resolve the following expression, and guess what the result would be!

var another_result = “hello” + undefined + 1

What would be the result of another_result ?

Reference

--

--