Some operations in javascript returns unexpected results. One is extremely strange:
[] + 1 = "1"
Can anybody explain why it works like that?
Some operations in javascript returns unexpected results. One is extremely strange:
[] + 1 = "1"
Can anybody explain why it works like that?
Javascript's rules for addition between differeent types are as follows:
Given the following addition.
To evaluate this expression, the following steps are taken (§11.6.1): Convert both operands to primitives (mathematical notation, not JavaScript):
PreferredType is omitted and thus Number for non-dates, String for dates. If either prim1 or prim2 is a string then convert both to strings and return the concatenation of the results.
Otherwise, convert both prim1 and prim2 to numbers and return the sum of the results.
Source
In this case the array gets converted to an empty string, and then the + performs string concatenation
[]
are converted to an empty string due to + operator. so "" + 1 => "1" (number converted to string too)ECMAScript 11.6.1 defines addition. Steps 5 and 6 of addition call
ToPrimitive
(9.1) for each operand and operate on those results:For an array (or any object),
ToPrimative
calls thetoString
method of the object. The result of callingtoString
on an empty array is the empty string (per the behavior described in 15.4.4.2.For a number,
ToPrimitive
returns the number (since numbers are already primitive).We're left adding the empty string and the number 1. When either operand in addition is a string, the addition acts as a concatenation operation (per addition's step 7), so we end up with
"" + "1" = "1"
.