Why is this line valid in javascript ?
var a = 0[0];
After that, a is undefined.
Like most programming languages, JS uses a grammar to parse your code and convert it to an executable form. If there's no rule in the grammar that can be applied to a particular chunk of code, it throws a SyntaxError. Otherwise, the code is considered valid, no matter if it makes sense or not.
The relevant parts of the JS grammar are
Literal ::
NumericLiteral
...
PrimaryExpression :
Literal
...
MemberExpression :
PrimaryExpression
MemberExpression [ Expression ]
...
Since 0[0] conforms to these rules, it's considered a valid expression. Whether it's correct (e.g. doesn't throw an error at run time) is another story, but yes it is. This is how JS evaluates expressions like someLiteral[someExpression]:
someExpression (which can be arbitrary complex)Number, strings => String etc)get property operation on result(2) with the property name result(1)So 0[0] is interpreted as
index = 0
temp = Number(0)
result = getproperty(temp, index) // it's undefined, but JS doesn't care
delete temp
return result
Here's a example of a valid, but incorrect expression:
null[0]
It's parsed fine, but at run time, the interpreter fails on step 2 (because null can't be converted to an object) and throws a run time error.