简体   繁体   中英

Why does 1+[ ] return “1” in JavaScript?

Recently one of my friends asked me a question:

![]+1+[]+false

going with my instincts after evaluation I answered 2 . But when I tried the expression in browser console the output I get is "1false" .

for me the weird part is 1+[] which evaluates to "1" ?

I couldn't understand why is that and how is it working?

Can someone please explain?

Thanks

Adding a number and an object, tries to convert the object to a primitive. To do that, it calls .toString() on the object, the empty array in this case, and for arrays that calls .join() , and [].join() is "" , and thus 1 + [] is the same as "1" .

Also keep in mind that additions go from left to right.

 (![]) + 1 + [] + false // objects are truthy, therefore *not object* is false
 (false + 1) + [] + false // boolean gets coerced to number, and false is 0
 (0 + 1) + [] + false // 0 + 1 is 1
 (1 + []) + false // .valueOf() as described above
 (1 + "") + false
 "1" + false
 "1false"

Since JavaScript is a weakly-typed language, values can also be converted between different types automatically when you apply operators to values of different type, and it is called implicit type coercion.

In general the algorithm is as follows:

  1. If input is already a primitive, do nothing and return it.
  2. Call input.toString(), if the result is primitive, return it.
  3. Call input.valueOf(), if the result is primitive, return it.
  4. If neither input.toString() nor input.valueOf() yields primitive, throw TypeError.

Numeric conversion first calls valueOf (3) with a fallback to toString (2).
String conversion does the opposite: toString (2) followed by valueOf (3).

+ operator triggers numeric conversion.

so valueOf will be called for blank array, which is blank array only. [].valueOf() // [] . Since valueOf is not primitive it will call [].toString() //""

so 1 + [] will convert to 1 + "" .

Since one of the operands is string operator triggers string conversion for 1.

so 1 + "" will convert to "1" + ""

And hence you get the output "1"

If at least one operand is string type, the other operand is converted to string and the concatenation is executed.

So in this case 1+[] -

[].toString() gives the empty string and the 1 will be stringified and you get the output "1"

further false also will be stringified and "1"+false = "1false"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM