output of the following program

What will be the output of the following program?

var z = {};
var x = { id: 10 };
y = { id: 20 };

z[x] = 'Anil'
z[y] = 'Singh'

console.log(z[x]);
console.log(z[y]);

Answer is  -

 In Detailed Explanation:

Because you are adding an object key to the z object. So when you do z[x] = 'Anil' the z object becomes

z: {
[object object]: 'Anil'
}

KEEP IN MIND: When you use objects as keys the key will be [object object]. So when you do z[y] it overrides the key "[object object]" with 'Singh'.

So in the end the object z has a key "[object object]" and a value 'Singh'.

Finally, when you do console.log you log twice the key. With what in mind, if you create another object another = {hello: ‘world’} and you console.log (z[another]) you will again get ''Singh".
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^