What does {x: 1} do in Javascript?

From Javascript: A Complete Guide,

var o = { x:1 }; // Start with an object ox = 2; // Mutate it by changing the value of a property oy = 3; // Mutate it again by adding a new property 

What is {x: 1} doing here? With curly braces, this reminds me of a function (or for objects, a constructor). Can someone comment on this, thanks.

Additional related question:

 ({x:1, y:2}).toString() // => "[object Object]" 

I also find this question interesting. What is the difference between an object and an object in the above code? Actually, when do we use Object?

+6
source share
4 answers

It turns the variable o into an object containing one property ( x ), and sets the value of this property to 1.

Edit

To be clear, as you have demonstrated, you do not need to add properties this way. You can create a property on an object by simply assigning it ( oy = "Awesomesauce" )

Regarding your related question; {x:1, y:2} is just an object literal with two properties x and y with values ​​1 and 2 respectively. working on this object is literally like working on a primitive value of values ​​( console.log("my,string".split(",")) ).

"[object Object]" is how a non-specifically typed object is represented in string form.

Edit 2

According to your comment: the lowercase "object" is a type. typeof o will give an object . The object (capital "O") is just a string representation of {x:1} . The string representation of an array or number is smart because it knows the type more accurately. Using a special object such as o , it simply is a shared object and thus writes: object (the type) Object (a string representation of o itself)

+11
source

It is called an object initializer (at least in C #). It creates a new o object and directly initiates the x attribute with a value of 1

+4
source

This is a JSON object, an associative array. The key is "x"; the value is 1.

+3
source

You already have the answers to the first part of your question.

In the second part, you called the toString() method stored in Object.prototype .

For fun, try this instead:

 JSON.stringify({x:1, y:2}) 
+2
source

Source: https://habr.com/ru/post/894462/


All Articles