Symbol in JavaScript

Symbols are a primitive data type introduced in ECMAScript 6 (ES6). A symbol is a unique and immutable data type that can be used as an identifier for object properties. Symbols are often used to create private object properties or to prevent naming conflicts in object properties.

Symbol in JavaScript

// Creating a symbol
const mySymbol = Symbol();

// Symbols can also have a description (optional)
const namedSymbol = Symbol('mySymbolDescription');

Symbols are guaranteed to be unique, even if they have the same description. For example:

const symbol1 = Symbol('mySymbol');
const symbol2 = Symbol('mySymbol');
console.log(symbol1 === symbol2);  // false

Symbols are often used as keys for object properties, especially in scenarios where you want to create "private" properties or avoid naming conflicts:

const myObject = {};
// Using a symbol as a key
const mySymbol = Symbol('myProperty');
myObject[mySymbol] = 'This is a private property';
console.log(myObject[mySymbol]);  // This is a private property

Symbols are not enumerable in for...in loops, which means they won't be accidentally iterated over when you loop through the properties of an object. This makes them suitable for scenarios where you want to hide certain properties.

for (let key in myObject) {
  console.log(key);  // This will not log the symbol, as symbols are not enumerable
}

Symbols also have built-in properties accessible through Symbol's properties:

console.log(Symbol.iterator);  // Symbol(Symbol.iterator)
console.log(Symbol.for('myKey'));  // Retrieves a symbol key from the global symbol registry

Also, note that symbols alone do not make a property truly private or secure; they just make it less likely to be accessed unintentionally. Additionally, symbols do not prevent access to an object's properties using methods like Object.getOwnPropertySymbols() or Reflect.ownKeys().


Similar Articles