Reputation: 622
While practising few examples , I encountered the following example :
var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object[foo] = 'value';
alert(object[bar]);
where two objects foo and bar are created . I am not getting how alert(object[bar]); is "value". Whats the link here between foo and bar.
Also, a slight variation would give the output as "undefined" as the example below.
var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object["foo"] = 'value';
alert(object[bar]);
By default , the []
notation can use the strings right , arent ["some_property"]
and [some_property]
the same?
Upvotes: 3
Views: 77
Reputation: 92511
An object's keys can only be strings*, so when you access an object's property using value which is not a string, it gets converted to a string.
In ECMAScript 6 you can use Map, which is similar to objects, but you can use any value as a key. Example:
const foo = {unique_prop: 1}
const bar = {unique_prop: 2}
const map = new Map()
map.set(foo, 'value')
console.log(map.get(bar)) // undefined
* In ECMAScript 6 you can also use symbols, but that's not relevant here.
Upvotes: 0
Reputation: 2152
When using square bracket notation, anything inside the square brackets is converted into a string. Then that string is used to look for a property called the same thing.
var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object[foo] = 'value';
// foo is an object, so it's automatically turned into the string "[object Object]"
// so the above code is equivalent to `object["[object Object]"] = 'value';`
alert(object[bar]);
// bar is also an object, so is converted into the same string
// the above code is also equivalent to `alert(object["[object Object]"]);` which of course accesses that same value
var blah = "not blah";
object.blah = 1;
object["blah"] = 1;
object[blah];
// a variable is used.
// therefore the value of that variable is what the assessor is looking for, not the name of the variable.
// so the above code is equivalent to `object["not blah"];`.
Upvotes: 6