2

I was given a short javascript code in an interview to give the output of that but I was not sure what will be the output of that. He creates a var object and assigns objects as indexes of that object using the array data structure. I did console that code after the interview but still do not understand how it is showing the output.

Here is the code

var a = {};
b = { key: 'b'};
c = { key: 'c'};
a[b] = 123;
a[c] = 456;

console.log(a[b]); //what is the output of this console statement and explain why

Can anyone explain with javascript logic behind the output it shows? Thanks in advance!

Suleman Ahmad
  • 452
  • 1
  • 5
  • 14
  • There's no array in your example. `a`, `b` and `c` are all objects – Andreas Aug 23 '21 at 10:51
  • Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – David Arias Aug 23 '21 at 10:52
  • yes but when assigning it with number there is array data structure is used – Suleman Ahmad Aug 23 '21 at 10:52
  • @DavidArias I have to look into that. – Suleman Ahmad Aug 23 '21 at 10:54
  • 2
    You can access the properties of an object with the dot notation (`b.key`) or with the bracket notation (`b["key"]`). The bracket notation has to be used when the property name is not a valid identifier (e.g. when there's a space in the name) -> [Property accessors - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) – Andreas Aug 23 '21 at 10:54

2 Answers2

4

The object used as key's toString is [object Object] and that is what is used each time

var a = {};
b = { key: 'b'};
c = { key: 'c'};
a[b] = 123; // sets a["[object Object]"]
console.log(b,a[b])
a[c] = 456; // ALSO sets a["[object Object]"]
console.log(b,a[b])
console.log(Object.keys(a))
console.log(a[b]);

console.log(a["[object Object]"]);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

You could have a look to the object a, where you see the stringed object (with toString())

[object Object]

as accessor.

Objects can have only strings as properties and with the latest Symbol, it could be this one, too.

var a = {};
b = { key: 'b'};
c = { key: 'c'};
a[b] = 123;
a[c] = 456;

console.log(a[b]); //what is the output of this console statement and explain why
console.log(a);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392