JavaScript Symbols

The typeof operator in JavaScript is used to determine the type of a variable or an expression. It returns a string indicating the data type of the operand.

In JavaScript, a symbol is a primitive data type introduced in ECMAScript 6 (ES6). Symbols are unique and immutable, providing a way to create unique identifiers that are guaranteed to be distinct from other values. Here's an explanation of symbols with a code example:

Creating Symbols

You can create a symbol using the Symbol()function, which returns a new, unique symbol value.


let sym1 = Symbol();
let sym2 = Symbol("descrative");
console.log(sym1);// Output: Symbol()
console.log(sym2);// Output: Symbol(description)

In the example above, sym1 and sym2 are two distinct symbols. The optional parameter passed to Symbol() is a description, which can be useful for debugging but does not affect the uniqueness of the symbol.

Uniqueness of Symbols

Each symbol created by Symbol()is unique, even if they have the same description.


let sym1 = Symbol("foo");
let sym2 = Symbol("foo");
console.log(sym1 === sym2);// Output: false

Despite having the same description ("foo"), sym1 and sym2are distinct symbols and are not equal to each other.

Using Symbols as Object Properties

Symbols can be used as property keys in objects. These properties are non-enumerable, meaning they won't appear in for...inloops or Object.keys().


let sym = Symbol("kay");

let obj = {
  [sym]:"value"
};
console.log(obj[sym]);// Output: "value"
console.log(Object.getOwnPropertySymbols(obj));// Output: [Symbol(key)]

In the above example, symis used as a property key in the object obj. The value of the property can be accessed using bracket notation with the symbol as the key. Object.getOwnPropertySymbols()retrieves an array of all symbol properties of an object.

Symbol Registry

Symbols can be stored in a global symbol registry, allowing symbols with the same description to be shared across the application.


let sym1 = Symbol.for("foo");
let sym2 = Symbol.for("foo");

console.log(sym1 === sym2);// Output: true

In this case, both sym1 and sym2refer to the same symbol because they were created using Symbol.for() with the same description.