Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I directly access a property of an object literal?

Tags:

Why the following syntax

{a:1,b:2}.constructor 

is invalid, whereas

[1,2].constructor  

is valid?

like image 210
Unknown developer Avatar asked Mar 11 '16 15:03

Unknown developer


People also ask

How do you access the properties of objects in typescript?

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

How do you use object literals?

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.

Why is object property undefined JavaScript?

The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.


2 Answers

{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 
like image 180
elclanrs Avatar answered Sep 22 '22 10:09

elclanrs


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.

like image 35
Grundy Avatar answered Sep 22 '22 10:09

Grundy