Why is 0[0] syntactically valid?

后端 未结 7 693
天涯浪人
天涯浪人 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:24

    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]:

    1. evaluate someExpression (which can be arbitrary complex)
    2. convert the literal to a corresponding object type (numeric literals => Number, strings => String etc)
    3. call the get property operation on result(2) with the property name result(1)
    4. discard result(2)

    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.

提交回复
热议问题