Question presented to candidate: "What is a Symbol in JavaScript, and can you show a real, practical reason you'd use one as an object property key instead of a string?"
What a strong answer should cover:
- 📌 Interview term:
Symbol()— creates a new, genuinely unique primitive value every single time it is called, even when given the identical description string — verified directly: two separateSymbol("id")calls are genuinely not equal to each other. - 📌 Interview term: collision-free property keys — the real, practical use case: a symbol-keyed property genuinely cannot accidentally collide with any other property, string-keyed or otherwise, and it is genuinely excluded from
Object.keys(),for...in, andJSON.stringify()— verified directly, making symbols useful for attaching "hidden," non-enumerable-by-default metadata to an object without polluting its normal, visible key space. - 📌 Interview term: well-known symbols — built-in symbols like
Symbol.iteratorthat let a class opt into a JavaScript protocol — verified directly: implementing[Symbol.iterator]()on a custom class genuinely made it work correctly with spread syntax ([...instance]) and, by extension,for...of. - 📌 Interview term:
Symbol.for()— the registered/global-registry exception — verified directly: unlike plainSymbol(),Symbol.for("key")genuinely returns the SAME symbol for the same key across separate calls, since it looks the key up in (and adds it to) a shared, global registry rather than creating a new unique value each time. - A precise answer names that a symbol-keyed property is still genuinely retrievable if truly needed via
Object.getOwnPropertySymbols()— it is hidden from casual enumeration, not cryptographically secret or truly private (private class fields, covered in this bank's own dedicated question, are the genuinely private mechanism).
Clarifying questions expected:
- None — this is a definitional/technical question; naming a real, concrete use case (well-known symbols or collision-free keys) beyond "it's a new primitive type" is the strong signal.
Code / implementation expected: Yes — implementing Symbol.iterator on a real custom class, verified working with spread syntax, is the clearest, most convincing demonstration of a genuine practical use.