[Javascript] The hidden transform in Javascript
[] + []
Answer: ""
Both arrays ([]) are first converted to their string representations before the + operator is applied. In JavaScript, arrays are converted to strings by concatenating their elements with commas in between. Since the arrays are empty, their string representations are empty as well.
[] + ![]
Answer: "false"
-
![]is evaluated first:- In JavaScript,
[](an empty array) is truthy, so![]evaluates tofalse.
- In JavaScript,
-
Now the expression becomes
[] + false:- The
+operator, when used with an array and a non-array value, coerces both operands to strings. [](empty array) is coerced to an empty string"".falseis coerced to the string"false".
- The
-
String concatenation:
"" + "false"results in"false".
Object to primitive
Let's go deep to understand why is so in low level
obj + obj = ?
When javascript see +operator, it will first convert Object to primitive type, it follow rules:
First, will check whether has [Symbol.toPrimitive]: fn ()
const obj = {
[Symbol.toPrimitive]: function () {
return 'wef' // here return value has to be a primitive type, if you return {},[], it will throw error
}
}
console.log(obj + 1) // wef1
If we don't have [Symbol.toPrimitive], then it will check valueOf()
const obj = {
valueOf() {
return 'wef' // has to be primitive value
}
}
console.log(obj + 1) // wef1
Lastly we check against toString()
const obj = {
valueOf() {
return {} // won't throw error, but also it won't be able to convert to primitive
},
toString() {
return "wef"
}
}
console.log(obj + 1) // wef1
If all of those do not exist, then it throw TypeError: Cannot convert object to primitive value
Now let's back to the question and try again
[][Symbol.toPrimitive] // undefined
[].valueOf() // [], not a primitive
[].toString() // ''
[1,2,3].toString() // '1,2,3'
[] + [] // '' + '' = ''
But ![] is different! It not doing object to primitive convertion, it's doing boolean check. And ![] is false
[] + ![] // '' + false = 'false'
For boolean check, those values are consdiered as falsey value
null, undefined, 0, NaN, false, ""

浙公网安备 33010602011771号