JavaScript Interview Question #124
What are Symbol values used for?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
A Symbol is a primitive value that is guaranteed to be unique when created with Symbol(). Symbols can be used as object property keys without colliding with ordinary string keys.
Detailed Explanation
A Symbol is a primitive value that is guaranteed to be unique when created with Symbol(). Symbols can be used as object property keys without colliding with ordinary string keys.
JavaScript also defines well-known symbols such as Symbol.iterator that allow objects to participate in language protocols. Symbols are useful for specialized metadata and protocol customization, although private class fields are generally more appropriate for true class-private state.
Code Example
const internalId = Symbol("id");
const user = {
name: "Asif",
[internalId]: 123
};
console.log(user[internalId]); // 123
console.log(Object.keys(user)); // ["name"]