Skip to content

Javascript Addition Operator (+)

Posted on:September 25, 2023 at 10:25 AM

You might have encountered something strange in javascript when you try to add string into number, it concatenates rather throwing error. Why is that?

Table of contents

Open Table of contents

Addition Operator (+)

10 + "10"; // 1010

Because whenever one operand is string and other operand is number, Js converts number into string and then concatenates. So whenever you encounter (+) operator in JS, (+) operator either performs string concatenation or numeric addition.

Rules

Before we jump into examples, Let’s try to understand how to convert non primitives into primitives. Two methods are used to convert non-primitives into primitives.

toString();
valueOf();

The theme-color meta tag has been added to dynamically adapt to theme switches, ensuring a seamless user experience.

Examples

var today = new Date();
var number = 10;
var result = today + number;
console.log(result);

What do you think should be the result? It will give you string “Sat Apr 04 2020 15:01:55 GMT+0530 (India Standard Time)10”

(check the rules for reference) First JS converts date into string and converts number into string and then concatenates.

20 + "20"; // "2020" (converts number into string and then concatenates)

20 + true; // 21
// one operand is number so Js converts true into number, which is 1

20 + false; // 20
// false become 0 and then two operands are number so js performs numeric operation

20 + "false"; // "20false"
// one operand is string so converts other operand into string and then performs
// string concatenation.

20 + undefined; // NaN
// one operand is number so JS converts undefined into number which is NaN
// you can check by Number(undefined) in the browser
// any number + NaN gives you NaN

20 + null; // 20
// one operand is string so Js converts null into number which is 0.
// you can check typing Number(null) in the browser console.
// 20 + 0 = 20

20 + "null"; // "20null"
// I know you guys must have figured it out the answer.

Below examples are addition operator on primitive with non-primitive(Object) types.

20 + {}; // "20[object Object]"
// Check rule number 1
// Js converts non-primitives into primitives
// String({}) gives you "[object Object]"
// Now we have a 20 + "[object Object]"
// number will be converted into string and then concatenates

20 + []; // "20"
// here also apply rule no 1
// String([]) gives you "" (empty string)
// 20 + ""
// 20 gets converted into "20"
// "20" + ""
// "20"

[1, 2] + 20; // "1,220"
// String([1,2]) gives you "1,2"
// "1,2" + 20
// "1,2" + "20"
// "1,220"

20 + [1, 2, 3]; // "201,2,3"
// You must have figured it out the answer.

20 + [""]; // "20"

20 + [" "]; // "20 "