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)
Advertisement
Answer
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)