Javascript symbol
Created By: chatGPT
JavaScript Symbols are a unique and immutable data type introduced in ECMAScript 2015 (ES6). They are often used to create unique identifiers for object properties and help avoid name clashes. Each symbol is unique, even if they have the same description. Here’s how to create and use symbols:
const uniqueSymbol1 = Symbol('description1');
const uniqueSymbol2 = Symbol('description1');
console.log(uniqueSymbol1 === uniqueSymbol2); // false
Symbols can be heavily utilized in scenarios where you need private properties. You can use symbols as keys to object properties, ensuring they don't clash with others. For example:
const mySymbol = Symbol('mySymbol');
const obj = {
[mySymbol]: 'value'
};
console.log(obj[mySymbol]); // value
JavaScript also has a few built-in symbols that can help with certain behaviors, like
Symbol.iterator
, which allows an object to define its default iterator. Here’s how to implement it:const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
for (const value of myIterable) {
console.log(value); // 1, 2, 3
}
Using symbols can enhance privacy and encapsulation in your JavaScript code, as they are not easily accessible like regular object properties. Keeping this in mind can improve the structure and maintainability of your code. To explore all the symbols in an object, you can use
Object.getOwnPropertySymbols()
.const anotherSymbol = Symbol('anotherSymbol');
const anotherObj = {
[mySymbol]: 'hidden',
[anotherSymbol]: 'also hidden'
};
const symbols = Object.getOwnPropertySymbols(anotherObj);
console.log(symbols); // [Symbol(mySymbol), Symbol(anotherSymbol)]