Search code examples
javascriptsyntax-error

Why 1[''] evaluates to undefined, but 1[] throws `Uncaught SyntaxError: Unexpected token ']`


How is Javascript interpreting the expression 1[''] as undefined, yet 1[] throws Uncaught SyntaxError: Unexpected token ']?

console.log(1[''])

console.log(1[])


Solution

  • The subscript operator ([]) is used to access an object's properties.

    1 is a number literal, which is evaluated as a Number object when followed by ['objectPropertyName']. It does not have a property '', and thus returns undefined when you call 1[''].

    1[], on the other hand, is just a syntax error - you can't omit the property you're trying to access. In other words, you have to have something in the braces.