Why the following syntax
{a:1,b:2}.constructor
is invalid, whereas
[1,2].constructor
is valid?
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function.
The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.
{a:1,b:2}.constructor
is not invalid syntax, but it is ambiguous, because {}
denotes a block, or an object? So you have to disambiguate the expression with parentheses, like ({a:1,b:2}).constructor
. Now JavaScript knows you meant to use an object.
If you use that syntax in a context where it is clearly an object, then there is no ambiguity:
console.log({a:1,b:2}.constructor) // works fine
Curve brackets at the start of a line is recognized as a code block instead of an object literal.
If you look at the error in the console, you can see Uncaught SyntaxError: Unexpected token :
. So, the error is not in calling the constructor property.
Also, when you write in the console
{a:1}
JS interprets this as a block with a label and not an object with property a
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With