zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Difference between [ ]+{ } and { }+[ ] in JavaScript

1668517551012

[ ]+{ }: An array plus an object.

The addition operation will perform implicit type conversion, following the rule of calling either valueOf() or toString() to obtain a non-object value (primitive value).

If either of the two values is a string, string concatenation will be performed; otherwise, numeric addition will be carried out. Both [ ] and { } return the object itself from valueOf(), leading to the invocation of toString(), resulting in string concatenation.

[ ].toString() returns an empty string, while ({ }).toString() returns "[object Object]", hence the final result is "[object Object]".

{ }+[ ]: Appears to be similar to the above.

However, besides representing an object, { } can also denote an empty block. In [ ] + { }, [ ] is interpreted as an array, so the subsequent + is parsed as an addition operator, and { } is interpreted as an object.

But in { } + [ ], { } is parsed as an empty block, and the following + is interpreted as a unary plus operator. Essentially, it becomes: {∥empty block}+[ ], which means performing a unary plus operation on an empty array, resulting in the array being converted to a number. Initially, calling valueOf() returns the array itself, which is not a primitive value, so [ ].toString() is then called, returning an empty string. Converting an empty string to a number yields 0, which is the final result.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.