Interview question on JS

This is the question:

What is the output of the following code

let a ={}
let b = {key: 'b'}
let c = {key: 'c'}
a[b] = 78
a[c] = 34
console.log(a[b])

The answer for me was 78 but it turns out to be wrong and I don’t know why… BTW This comes from: medium.com

I assume what is happening…

When it tries to evaluate those key/property names, in like a[b], the key has to be a string. Since b is not a string (it is an object), JS tries to convert it to a string. It sees that it is an object to it runs the toString method, which evaluates to the string “[object Object]”. That is the key that gets set in a[b] = 78. So, since c will evaluate to the same string, it overwrites that value.

Put:

console.log(b.toString())
console.log(c.toString())
console.log(a)

at the bottom to see what I mean.

That’s what we call a “gotcha question”. :wink:

2 Likes

When in doubt, check the docs.

From this page:

JavaScript object property names (keys) can only be strings or Symbols — all keys in the square bracket notation are converted to strings unless they are Symbols. For example, in the above code, when the key anotherObj is added to the myObj, JavaScript will call the toString() method of anotherObj, and use the resulting string as the new key.

1 Like
let a ={}
let b = {key: 'b'}
let c = {key: 'c'}
let d = {keyy: 'e'}
a[b] = 78
console.log(a)
a[c] = 34
console.log(a)

'tis an interestin one

1 Like

Professor @kevinSmith , Many, many thanks for your help and answering my question. Indeed, I rewrote the code to see what happens:

let a ={}
let b = {key: 'b'}
let c = {key: 'c'}
a[b] = 78
a[c] = 34
console.log(b.toString())
console.log(c.toString())
console.log(a)
console.log(a[b])

If I erase the line a[c] = 34 then I see what you are explaining: The object is not overwritten and the result is 78

Right, the important point here is that if you try to use an object as a key, then it will convert it to a string, which will usually be “[object Object]”, so all objects will evaluate to the same key.

Remember that only strings and Symbols can be used as keys. Numbers can too, but JS will see that it is not a string, see that it is not a reference type (so has no toString method) will see if it has an object wrapper (it does, Number), will wrap it in that, and run the toString for that new object, which will yield a string representation of that number - a more predictable result.

If you don’t know what Symbol is - don’t worry, it doesn’t come up much except in more advanced applications.

1 Like