Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: array plus number [duplicate]

Tags:

javascript

Some operations in javascript returns unexpected results. One is extremely strange:

[] + 1 = "1"

Can anybody explain why it works like that?


2 Answers

[] are converted to an empty string due to + operator. so "" + 1 => "1" (number converted to string too)

like image 70
peernohell Avatar answered Dec 23 '25 18:12

peernohell


Javascript's rules for addition between differeent types are as follows:

Given the following addition.

value1 + value2

To evaluate this expression, the following steps are taken (§11.6.1): Convert both operands to primitives (mathematical notation, not JavaScript):

prim1 := ToPrimitive(value1)
prim2 := ToPrimitive(value2)

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

like image 35
Ben McCormick Avatar answered Dec 23 '25 19:12

Ben McCormick