Home
← All questions

Output question: object keys are coerced to strings in JavaScript

MediumPremiumJavaScript

JavaScript interview practice: Predict the output when objects are used as object keys.

Problem

Output questions about object keys in JavaScript come up constantly in frontend interviews because they test whether you understand how property access really works, which matters when using objects as lookup tables or caches.

What does the following code log, and why?

const a = {};
const b = { key: "b" };
const c = { key: "c" };

a[b] = 100;
a[c] = 200;

console.log(a[b]); // ?

Requirements

  • State the exact value logged by console.log(a[b]).
  • Explain step by step what happens on each assignment and on the final read.
  • Explain what Object.keys(a) would contain after the two assignments.
  • Suggest a built-in alternative you would use if you genuinely needed objects as keys, and explain why it behaves differently.

Example

Answer these related questions as well:

// Follow-up 1: what does this log?
const obj = {};
obj[1] = "number";
obj["1"] = "string";
console.log(obj[1], Object.keys(obj).length); // ?
// Follow-up 2: what does this log?
const store = {};
const key = { toString() { return "id-42"; } };
store[key] = "saved";
console.log(store["id-42"]); // ?

Follow-ups

  • Would the answer change if b and c were arrays such as [1] and [2]?
  • Would the answer change if b and c were Symbol values?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium