Middle
What is the Symbol type in JavaScript and what is it used for?
sobes.tech AI
Answer from AI
A new primitive data type introduced in ES6 (ES2015). It guarantees the uniqueness of each created value.
Used for:
- Creating unique object properties: This prevents name collisions, especially when adding properties to objects that may be extended by third-party code.
const mySymbol = Symbol('my description'); const obj = {}; obj[mySymbol] = 'unique value'; // Access via symbol console.log(obj[mySymbol]); // Not visible during normal iteration (except Object.getOwnPropertySymbols) for (const key in obj) { console.log(key); // Will not output anything } - Definition of well-known symbols: Built-in symbols used by the JavaScript engine to define internal object behaviors (e.g.,
Symbol.iterator,Symbol.toStringTag).const arr = [1, 2, 3]; // Allows iteration with for...of loop const iterator = arr[Symbol.iterator](); console.log(iterator.next()); // { value: 1, done: false } - Hiding implementation details: Symbols do not appear in
for...inloops orObject.keys(), helping to hide internal properties. Access is only possible throughObject.getOwnPropertySymbols().const privateSymbol = Symbol('private'); const myObject = { name: 'Public', [privateSymbol]: 'Private Value' }; console.log(Object.keys(myObject)); // [ 'name' ] console.log(Object.getOwnPropertySymbols(myObject)); // [ Symbol(private) ]