FrontendDeveloper.in

ECMAScript question detail

Symbols

Symbol is a new peculiar primitive data type of JavaScript, along with other primitive types such as string, number, boolean, null and undefined. The new symbol is created just by calling the Symbol function. i.e, Every time you call the Symbol function, you’ll get a new and completely unique value. You can also pass a parameter to Symbol(), which is useful for debugging purpose only.

Even though equality checks on two symbols is always false, it will be true while comparing symbols with .for method due to global registry (i.e, Symbols.for('key') === Symbols.for('key'))

These symbols are useful to uniquely identify properties or unique constants,

//1. Object properties
let id = Symbol("id");
let user = {
name: "John",
age: 40,
[id]: 111
};

for (let key in user) {
console.log(key); // name, age without symbols
}

console.log(JSON.stringify(user)); // {"name":"John", "age": 40}
console.log(Object.keys(user)); // ["name", "age"]

console.log( "User Id: " + user[id] ); // Direct access by the symbol works

//2. Unique constants
const logLevels = {
DEBUG: Symbol('debug'),
INFO: Symbol('info'),
WARN: Symbol('warn'),
ERROR: Symbol('error'),
};
console.log(logLevels.DEBUG, 'debug message');
console.log(logLevels.INFO, 'info message');

//3. Equality Checks

console.log(Symbol('foo') === Symbol('foo')); // false
console.log(Symbol.for('foo') === Symbol.for('foo')); // true
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399