4

Our Beloved JavaScript can be very weird...

(![] + [])[+!+[] + +!+[]]                // 'l'
    + (![] + [])[+!+[]]                  // 'a'
    + ([![]] + [][[]])[+!+[] + [+[]]]    // 'i'
    + ([][[]] + [])[+!+[] + +!+[]]       // 'd'
 // Will output "laid"

The reason why JavaScript produces this output mainly depends on type casting of array and ability of + to cast 'things' into string. ![] // false while +[] // 0 my question is how did JavaScript successfully parse [][[]] to be undefined but reject [][][] as syntax error

1 Answer 1

6

[] means different things depending on the context

[][[]]

The first [] creates a new array (array literal syntax).

Then that_array[[]] tries to read a property from that array (square bracket property accessor syntax).

The property name is [] (also array literal syntax), which being an array, gets converted to a string: ''

Since there is no property named an empty string, it resolves to undefined.

In other words:

const array = [];
const propertyName = [].toString();
console.log(array[propertyName]);
[][][]

This errors because while the first [] creates an array, the second [] tries to access a property from it but fails to include a value for the property name. It has ] before the value, so the second ] is unexpected. It never gets to the third [].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.