Home > other >  Why doesn't this invalid syntax throw an error?
Why doesn't this invalid syntax throw an error?

Time:09-10

I would expect the code below to throw a syntax error, because of 'some string' [{}], but it just works fine. Although the property is undefined.

const object = {
  property: 'some string' [{}]
}

console.log(object)

This on the other hand throws an error as expected:

const object = {
  property: 'some string' []
}

console.log(object)

CodePudding user response:

The first is not invalid syntax. That code is looking for a property [object Object] (the {} is cast to a string).

The second is invalid syntax, because there is nothing in property access operator.

Note, however, that because this is string and not String, you cannot add custom properties yourself.

You can still lookup properties, because there is .length and also things on the prototype such as .slice() and .substring()

For example, if you add the custom property to the prototype, you can cheese this:

String.prototype["[object Object]"] = "banana";

const object = {
  property: 'some string' [{}]
}

console.log(object)

CodePudding user response:

You are really just attempting access on the string like this (with bracket notation):

property: 'some string'[{}]

Anything between the two brackets is evaluated and coerced to a string, so you'll actually get:

property: 'some string'['[object Object]']

and as we all know, strings do not have a [object Object] property.

Your second example is invalid, because there must be something between the brackets when using bracket notation.

  • Related