Why is this line valid in javascript ?
var a = 0[0];
After that, a
is undefined
.
I'd just like to note that this being valid syntax is not in any way unique to Javascript. Most languages will have a runtime error or a type error, but that's not the same thing as a syntax error. Javascript chooses to return undefined in many situations where another language might raise an exception, including when subscripting an object that does not have a property of the given name.
The syntax doesn't know the type of an expression (even a simple expression like a numeric literal), and will allow you to apply any operator to any expression. For example, attempting to subscript undefined
or null
causes a TypeError
in Javascript. It's not a syntax error - if this is never executed (being on the wrong side of an if-statement), it won't cause any problems, whereas a syntax error is by definition always caught at compile time (eval, Function, etc, all count as compiling).