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!

5
  • There's no array in your example. a, b and c are all objects Commented Aug 23, 2021 at 10:51
  • Does this answer your question? Dynamically access object property using variable Commented Aug 23, 2021 at 10:52
  • yes but when assigning it with number there is array data structure is used Commented Aug 23, 2021 at 10:52
  • @DavidArias I have to look into that. Commented Aug 23, 2021 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 Commented Aug 23, 2021 at 10:54

2 Answers 2

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]"]);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.