Why is 0[0] syntactically valid?

后端 未结 7 682
天涯浪人
天涯浪人 2020-12-04 13:48

Why is this line valid in javascript ?

var a = 0[0];

After that, a is undefined.

相关标签:
7条回答
  • 2020-12-04 14:39

    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).

    0 讨论(0)
提交回复
热议问题