Explain why '+ [] == 0' output 'true' in Javascript?

Explain why +[] == 0 gives the result 'true' in Javascript?

Please check the example.

 +[] == 0 ? alert(true) : alert(false); 

And also check. '1+[+[]]' will produce the result '10 '

+6
source share
2 answers

It will be rated as below,

1: +[] == 0+"" == 0

The + operator has the highest priority than == , so it will be evaluated first. Thus, when converting an array to a number, the ToPrimitive() function will be called by passing it as an argument. Since [] is an object , it will return the string ""

2: +"" == 00 == 0

An empty string will be converted to 0 . And a non-empty string will be converted to NaN , as we all know.

3: 0 == 0true

And finally, according to the abstract equality comparison algorithm , when both operands of the same type are compared, no further evaluation will occur, it will directly check for its equality and return the result.


And in your second case 1+[+[]] score will look like,

1: 1+[+[]] - ( +[] will be first converted to a primitive, since [] is an object)

2: 1+[+""] ( toPrimitive([]) will be "" )

3: 1+[0] ( 0 will be displayed when converting an empty string to a number)

4: 1+"0" ( toPrimitive([0]) will be "0" )

5: "10"

+8
source

JavaScript evaluates +[] == 0 as follows:

  • Operator
  • + [] : + tries to convert operand [] to a primitive value.
  • + [] : [] converted to a string using the toString() method, which is an alias for [].join(',') . The result is an empty string. ''
  • + '' : an empty string is converted to a number: Number('')0
  • + 0 becomes 0
  • Finally, the comparison is evaluated: +[] == 00 == 0true

Score '1+[+[]]' :

  • 1 + [ +[] ] (Convert [] to primitive: '' )
  • 1 + [ + '' ] (Convert '' to number: 0 )
  • 1 + [ + 0 ] ( + 0 is 0 )
  • 1 + [ 0 ] (The add operator forces the conversion of [0] to a primitive value: [0].toString()[0].join(',')'0' )
  • 1 + '0' (Since the second operand '0' is a string, also convert the first number 1 to a string: '1' )
  • '1' + '0' (Concatenation of simple strings)
  • '10'

Read also this article about the add statement.

+5
source

All Articles