Symbol
In JavaScript, Symbol
is a primitive data type introduced in ES6 (ECMAScript 2015). It represents a unique and immutable value that can be used as an identifier for object properties. Symbols are often used to add non-enumerable properties to objects or as keys in maps or sets. Here's an explanation of Symbol
with a code example:
// Creating a symbol
const mySymbol = Symbol();
console.log(typeof mySymbol); // Output: symbol
// Symbols are unique
const anotherSymbol = Symbol();
console.log(mySymbol === anotherSymbol); // Output: false
// Symbols with description (optional)
const namedSymbol = Symbol('mySymbol');
console.log(namedSymbol.toString()); // Output: Symbol(mySymbol)
// Using symbols as object properties
const obj = {};
const symbolKey = Symbol('myKey');
obj[symbolKey] = 'value';
console.log(obj[symbolKey]); // Output: value
// Symbols are not enumerable in for...in loops or Object.keys
for (let key in obj) {
console.log(key); // No output because symbols are not enumerable
}
console.log(Object.keys(obj)); // Output: []
// Getting symbols only from an object
console.log(Object.getOwnPropertySymbols(obj)); // Output: [Symbol(myKey)]
In this example, we create a Symbol
using Symbol()
and Symbol('myKey')
. Symbols are unique, so even if we create multiple symbols with the same description, they will be different. We then use symbols as property keys in an object. Symbols are not enumerable, meaning they won't be included in for...in
loops or Object.keys
. You can access symbol keys using Object.getOwnPropertySymbols()
.
Symbols are often used for creating non-colliding property keys in objects, as they are guaranteed to be unique and not conflict with other property names or symbols.
Leave a Comment