Home > Article > Web Front-end > Why does [[]][ []] [ []] return "10" in JavaScript?
Unveiling the Mystery Behind [[]][ []] [ []]'s Return Value
In the realm of JavaScript, the enigmatic expression [[]][ []] [ []] perplexes many with its seemingly nonsensical return value: "10". Delving into the depths of JavaScript's evaluation process, we embark on a journey to decipher this puzzle.
Initially, let's break down the expression:
++[[]][+[]] + [+[]]
Expanding [[]][ []]
In JavaScript, the expression [] evaluates to 0. This is because attempts to convert the operand into a number, and an empty array coerces to a string, which is then converted to a number resulting in 0.
Substituting [] with its equivalent, we get:
++[[]][0] + [+[]]
Evaluating [[]][0]
The operator increments its operand by one, so [[]][0] is equivalent to ([[]][0]) 1. Since [[]][0] retrieves the first element of the empty array, it returns another empty array. Thus, ([[]][0]) is equivalent to [], which we know yields 0.
Simplifying the Remaining Expression
Simplifying further, we obtain:
1 + [+[]]
JavaScript's Coercion Magic
JavaScript's coercion rules come into play when dealing with the addition of an array and a number. First, the array coerces to a string ("0"), and then the number coerces to a string ("1"). String concatenation results in the final outcome:
console.log("1" + "0") // "10"
Additional Context
The above is the detailed content of Why does [[]][ []] [ []] return "10" in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!