Rishabh Sharma
Rishabh Sharma

Reputation: 1

what does mean by this line of code in JS obj[{key:"value"}] = "value";

let obj = {};
            obj[{key:"instagram"}] = "Akrixa";
            obj[{key:"facebook"}] = "Coding with Akrixa";

            console.log(obj[{key: "instagram"}]);

This is a problem in which I'm confused with 2nd and 3rd line of code, what does by those lines?

Upvotes: 0

Views: 64

Answers (3)

Tiến Lê
Tiến Lê

Reputation: 11

I think because obj[{key:"instagram"}] and obj[{key:"facebook"}] are the same object. When assign value for it, it has the same value. More detail: How to create dictionary and add key–value pairs dynamically?. I wish its help you

Upvotes: 0

bel3atar
bel3atar

Reputation: 943

obj[{key:"instagram"}] = "Akrixa" is equivalent to obj[({key:"instagram"}).toString()] = "Akrixa" since objects are keyed by strings. So it's equivalent to obj["[object Object]"] = "Akrixa"

Upvotes: 2

Joe
Joe

Reputation: 79

The second line obj[{key:"instagram"}] = "Akrixa"; creates a key within your obj [{key:"instagram}] (which is an object inside an array) and then sets the value of that key to Akrixa, and the third line does the same but with a different key and value.

It might be better to use obj["instagram"] = "Akrixa" and obj["facebook"] = "Coding with Akrixa" as to avoid excessive complication, and you can then refer to it with obj["instagram"] etc.

let obj = {};
obj["instagram"] = "Akrixa";
obj["facebook"] = "Coding with Akrixa";
console.log(obj["instagram"]);

Upvotes: -1

Related Questions