1

How property value being assigned in below code:

var foo = {};
var bar = {};
var obj = {};

obj[foo] = "Nishan";
obj[bar] = "Manis";


console.log(obj[foo]);

Why it giving output "Manis"

var foo = {};
var bar = {};
var obj = {};

obj.foo = "Nishan";
obj.bar = "Manis";

console.log(obj.foo);

Output: "Nishan"

What is difference between declare property of object by using "." and "[]" Ex: obj.far = "Nish" and obj[far] = "Nish"

var foo = {};
var bar = {};
var obj = {};

obj.foo = "Nishan";
obj.bar = "Manis";

console.log(obj[foo]);

Giving undefined

2 Answers 2

6

An object is valid as a key only because it's converted to a string, and the string representation of an object is [object Object], so what you're doing is equal to

var obj = {};

obj[`[object Object]`] = "Nishan";
obj[`[object Object]`] = "Manis";

console.log( obj[`[object Object]`] ); // returns Manis

So basically you're overwriting the key / value pair as the string representation of foo and bar is the same thing, they are both converted to [object Object]

EDIT :

In the second and third example you do something like

var foo = {};

obj.foo = "something";

but when you're using dot notation you can declare any property you want, and the property foo on the object has nothing to do with the variable foo declared above, they are not even remotely related, you might as well do

var foo = {};

obj.didgeridoo = "something";

the relevance is the same, nothing.

Sign up to request clarification or add additional context in comments.

Comments

3

When you access a property using square bracket notation, you have to pass a string in.

foo and bar are both objects.

When you convert an object to a string, by default, you get a result like "[Object object]".

foo.toString() === bar.toString() so obj[foo] === obj[bar].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.