Asha
Asha

Reputation: 760

Javascript toString method on Property names

var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'anu';
console.log(object[bar]);

The above code outputs "anu".

toString method typecast the non-string object into string object.

In the above code object[bar] outputs the value as 'anu'.

Document says 'since both foo and bar are converted to the same string'

I can't able to understand the java script toString method on this code.

can anybody please explain how it works?

Upvotes: 0

Views: 127

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

When you use foo's value as a property name, it calls toString on the foo like object[foo.toString()] = 'anu', which if not overridden, will return the same value for every object, which is '[object Object]'

So actually you have a property which name is '[object Object]'. Below console.logs will assure that you have a property with name '[object Object]'.

var foo = {unique_prop: 1};

var object = {};

object[foo] = 'anu';

console.log(`foo.toString() - ${foo.toString()}`);
console.log(`object.toString() - ${object.toString()}`);
console.log(`object.toString() === foo.toString() ? - ${object.toString() === foo.toString()}`);

for(var prop in object) {
  console.log(prop);
}

Upvotes: 7

Related Questions