addition

The most important “rules” with addition in JavaScript

  1. Adding a non-numeric value to a numeric value will try to convert the non-numeric value to a numeric value, if possible. If not, both are converted to strings.
  2. Adding a non-numeric value to some value will convert both values to strings before adding them.

When one of the values in an addition is an object, array or function it will try to convert it to a primitive value.

  1. Execute the valueOf()-function and use that value if it is a primitive
  2. Execute the toString()-function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1 + "2" = "12"
1 + 1 + "2" = "22"
1 + "1" + "2" = "112"

1 + true = 2
1 + false = 1
true + true = 2
false + false = 0
"1" + true = "1true"
"1" + false = "1false"

const me = { name: "Charlie", age: 34 }
me + 1 = "[object Object]1"

[] + 1 = "1"
[1, 2, 3] + [4, 5, 6] = "1,2,3" + "3,4,5" = "1,2,34,5,6"

# Date.valueOf returns a numeric type, but a date will be transformed into a string type when using the + operator.
new Date(2020, 11, 1) + 12345 = "Tue Dec 01 2020 00:00:00 GMT+0100 (Central European Standard Time)12345"
new Date(2020, 11, 1) + "12345" = "Tue Dec 01 2020 00:00:00 GMT+0100 (Central European Standard Time)12345"
new Date(2020, 11, 1).toString() = "Tue Dec 01 2020 00:00:00 GMT+0100 (Central European Standard Time)"
new Date(2020, 11, 1).valueOf() = 1606777200000

undefined + 1 = NaN // undefined is converted to numeric => NaN
undefined + "1" = "undefined1"
null + 1 = 1 // null is converted to numeric => 0
null + "1" = "null1"
NaN + 1 = NaN
NaN + "1" = "NaN1"
Symbol(1) + 1 // TypeError: Cannot convert a Symbol value to a number
BigInt(1) + 1 // TypeError: Cannot mix BigInt and other types, use explicit conversions
BigInt(1) + "2" = "12"