Here's a JavaScript question. Is this a valid expression in JavaScript?
[0][0];
I call this the Eyeglasses Expression because it looks like a pair of eyeglasses. It's an interesting piece of code because it looks strange, but it's actually a valid JavaScript expression.
Not only is it a valid piece of JavaScript code, but it produces a valid JavaScript value as its result.
So what is the result of this expression? You could run the code to get the answer, but before you do that, I suggest that you try to figure it out by thinking about it.
Let's try to answer these questions about the Eyeglasses Expression:
- What's the structure of this expression? (what's the syntax tree?)
- What is the result of this expression when it gets evaluated?
Analyzing the left side
The left half of the eyeglasses is a value in square brackets:
[0];
When you encounter an expression that starts with a square bracket, with nothing before it, you can assume that it's an Array Expression.
In this case, it's an array with a single item which is the number 0.
The right half of the expression
On the right, we have the same thing repeated again. So is it another array?
We have a square bracket, which is how you write an array, but we're no longer looking at the beginning of an expression. We're now looking at a square bracket in the middle of an expression. This changes everything.
When we see a square bracket in the middle of an expression, we're looking at a member expression. That means we're accessing a member (or a property) of something.
Consider if we changed the example and replaced the left side with the variable left. It would look like this:
left[0];
Here, the square brackets indicate that we're accessing a property (the index 0) of the value left.
That's the same thing that we're seeing in our eyeglasses expression. But instead of a varible named left, the left side of the expression is the array [0].
What's the result value?
So, what's the result of this expression? Let's walk through what's happening.
- First, we create a new array with the expression
[0]. Our array has a single item, the number0. - Then, we follow that with a property access. We're accessing index
0, which means we're accessing the first element of the array. - Because the array's first element is
0, that's what we get as the result. We get the number0.
What we learned
I like the Eyeglasses Expression as an educational example because it tells us a few things about how JavaSript syntax works.
First of all, we learned that the square brackets can mean different things: they mean "array" when they're at the start of an expression, and they mean "access a property" when they're in the middle of an expression.
Second, we learned how this kind of expression gets parsed into a syntax tree.
Further reading
Learn more with these pages on my website: