[] + [] = "" empty array + empty array = empty string Why?

[] + [] = "?

Mar.24,2021

you can take a look at this:
http://www.cnblogs.com/ziyunf.

to put it simply:

[] + [] first calls the valueOf method of [] . If valueOf returns basic type , this primitive type value is used. If the returned type is not a basic type, the valueOf method is discarded and the toString method is called instead.

[].valueOf() => [] // 
[].toString() => "" // 

so [] + [] = "" + "="

you can write a simple example to verify it:

const a = [] // 
a.valueOf = () => 3 // valueOf
a + a // 6
a.valueOf = () => ([1, 2, 3])
a + a // ""
a.toString = () => 'haha'
a + a // 'hahahaha'
a.toString = () => ([1, 2, 3])
a + a // 

[].toString()+[].toString() === ""

see the following test and this link: http://www.cnblogs.com/ziyunf.

clipboard.png


this is caused by the implicit conversion of data by js's operators.

The + operator in

js will call the toString method on the data of the reference type and convert it to a string


http://www.jsfuck.com/ learn


The

binary operator'+ 'can add two numbers or do string concatenation
the conversion rules of the plus sign give priority to string concatenation
-the above is extracted from the sixth edition of the Rhino Book P70
this is caused by the rules of the plus operator
unless neither of the operands is a class string.

if the rule is to give priority to numeric arithmetic, then [] + [] is 0.
here implicitly converts both sides of the Operand into strings
and so on: [] = =! []
! Convert [] to a Boolean value

Menu