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 Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

What will be the output of the following program? What will be the output of the following program? Reviewed by Anil Singh on 10:49 PM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^