JavaScript addition operator in details

Introduction

JavaScript is an awesome language. I like it because of the flexibility: just do the things in a way you like: change the variable type, add methods or properties to object on the fly, use operators on different variable types and much more.

However the dynamism comes with a price. Developer needs to understand how to handle types conversion for different operators: addition (+), equality (== and ===), inequality (!= and !==), etc. Many operators have their own way to handle the type conversions.

The addition operator

One of the most commonly used operator is addition: +. This operator is used to concatenate strings or sum the numbers:
1) Strings concatenation:

The second object operand is converted to a string value. Because valueOf() method returns the object itself and not a primitive value, the toString() method is used, which returns string.
The second operand is now a string, thus the number is converted to string too. The concatenation of 2 strings is executed.

Example 5: Number and null

var result = 8 + null; // 8

Explanation:

8 + null (Because none of the operands is string, convert the null to a number 0 based on rule 3)

8 + 0 (Numbers addition)

8

Because operands are not objects or strings, null is converted to number. Then numbers sum is evaluated.

Example 6: String and null

var result = "queen" + null; // "queennull"

Explanation:

"queen" + null (Because none first operand is string, convert the null to a string "null" based on rule 2)

"queen" + "null" (Strings concatenation)

"queennull"

Because the first operand is a string, null is converted to string. Then the strings concatenation is done.

Example 7: Number and undefined

var result = 12 + undefined; // NaN

Explanation:

12 + undefined (Because none of the operands is string, convert the undefined to a number NaN based on rule 3)

12 + NaN (Numbers addition)

NaN

Because neither of the operands is object or string, undefined is converted to number: NaN. Making an addition between number and NaN evaluates always to NaN.

Conclusion

To avoid potential issues, do not use addition operator with objects, unless you clearly define toString() or valueOf() methods.
As seen in examples, the addition operator has many specific cases. Knowing the exact conversion scenario will help you to prevent future surprises.
Have a good coding day!