The Symbol
object in JavaScript was introduced in ECMAScript 6 and is a primitive data type. It provides a way to create unique and immutable values that can be used as keys in object properties.
In this post, I will explain the use of the Symbol
object in JavaScript with code snippets.
Creating a Symbol:
You can create a new Symbol
by calling the Symbol()
function without the new
keyword:
const sym1 = Symbol();
console.log(typeof sym1); // "symbol"
You can also pass a description string to the Symbol()
function, which is useful for debugging purposes:
const sym2 = Symbol("foo");
console.log(sym2); // Symbol(foo)
Note that each Symbol
value is unique, even if the description string is the same:
const sym3 = Symbol("foo");
console.log(sym2 === sym3); // false
Using Symbols as Object Keys:
One of the main use cases for Symbol
is as keys in object properties. Unlike strings, Symbol
keys are not enumerable, which means they are not returned by Object.keys()
or for...in
loops:
const obj = {};
const sym = Symbol();
obj[sym] = "foo";
console.log(obj); // { [Symbol()]: 'foo' }
console.log(Object.keys(obj)); // []
This makes Symbol
keys useful for storing metadata or other internal information in objects without polluting the object’s interface.
Using Symbols to Define Constants:
Another use case for Symbol
is to define constants that are unique and cannot be overwritten. You can create a Symbol
constant by defining it at the top level of a module:
// constants.js
export const MY_CONSTANT = Symbol();
// main.js
import { MY_CONSTANT } from "./constants.js";
const obj = {};
obj[MY_CONSTANT] = "foo";
console.log(obj); // { [Symbol()]: 'foo' }
Using Built-in Symbols:
JavaScript provides several built-in Symbol
values that are used by the language itself. For example, Symbol.iterator
is used to define an iterator for an object:
const arr = [1, 2, 3];
const iter = arr[Symbol.iterator]();
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.next()); // { value: 2, done: false }
console.log(iter.next()); // { value: 3, done: false }
console.log(iter.next()); // { value: undefined, done: true }
Another built-in Symbol
is Symbol.toStringTag
, which is used to customize the toString()
method of an object:
class MyClass {
[Symbol.toStringTag]() {
return "MyClass";
}
}
const obj = new MyClass();
console.log(obj.toString()); // [object MyClass]
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.