In this tutorial, you will learn about JavaScript symbol with the assistance of examples.
In this article, you will learn-
JavaScript Symbol
Before symbols were presented in ES6 as another sort of primitive, JavaScript used seven primary types of data, assembled into two classes:
- Primitives, including the string, number, bigint, boolean, null, and undefined data types
2. Objects, including more complex data structures, for example, arrays, functions, and regular JS objects
Beginning with ES6, symbols were added to the primitives group. Like any remaining primitives, they are immutable and have no techniques for their own.
The original purpose of symbols was to give internationally unique qualities that were kept private and for inner use as it were. Notwithstanding, in the last usage of this primitive sort, symbols ended up not being private, yet they did keep their worth uniqueness.
The JavaScript ES6 presented another primitive data type called Symbol. Symbols are immutable (can’t be changed) and are unique. For instance,
// two symbols with the same description const value1 = Symbol('hello'); const value2 = Symbol('hello'); console.log(value1 === value2); // false
Though value1 and value2 both contain the same description, they are different.
Creating a Symbol
You use the Symbol() function to create a Symbol. For example,
// creating symbol const x = Symbol() typeof x; // symbol
You can pass an optional string as its description. For example,
const x = Symbol('hey'); console.log(x); // Symbol(hey)
Access Symbol Description
To access the description of a symbol, we use the. operator. For example,
const x = Symbol('hey'); console.log(x.description); // hey
Add Symbol as an Object Key
You can add images as a key in an object using square sections []. For instance,
let id = Symbol("id"); let person = { name: "Salman", // adding symbol as a key [id]: 123 // not "id": 123 }; console.log(person); // {name: "Salman", Symbol(id): 123}
Symbols are not included in for…in Loop
The for…in loop does not iterate over Symbolic properties. For example,
let id = Symbol("id"); let person = { name: "Salman", age: 25, [id]: 12 }; // using for...in for (let key in person) { console.log(key); }
Output
name age
Advantage of Using Symbols in Object
In the event that a similar code piece is used in different programs, at that point it is smarter to use Symbols in the object key. This is on the grounds that you can use a similar key name in various codes and avoid duplication issues. For instance,
let person = { name: "Salman" }; // creating Symbol let id = Symbol("id"); // adding symbol as a key person[id] = 12;
In the above program, in the event that the individual object is likewise used by another program, at that point you wouldn’t have any desire to add a property that can be accessed or changed by another program. Thus by using Symbol, you make a remarkable property that you can use.
Presently, if the other program additionally needs to use a property named id, simply add a Symbol named id and there won’t be duplication issues. For instance,
let person = { name: "Salman" }; let id = Symbol("id"); person[id] = "Another value";
In the above program, even if a similar name is used to store values, the Symbol data type will have a unique worth.
In the above program, in the event that the string key was used, at that point, the later program would have changed the value of the property. For instance,
let person = { name: "Salman" }; // using string as key person.id = 12; console.log(person.id); // 12 // Another program overwrites value person.id = 'Another value'; console.log(person.id); // Another value
In the above program, the second user.id overwrites the previous value.
Symbol Methods
There are various methods available with Symbol.
Method | Description |
for() | Searches for existing symbols |
keyFor() | Returns a shared symbol key from the global symbol registry. |
toSource() | Returns a string containing the source of the Symbol object |
toString() | Returns a string containing the description of the Symbol |
valueOf() | Returns the primitive value of the Symbol object. |
Example: Symbol Methods
// get symbol by name let sym = Symbol.for('hello'); let sym1 = Symbol.for('id'); // get name by symbol console.log( Symbol.keyFor(sym) ); // hello console.log( Symbol.keyFor(sym1) ); // id
Symbol Properties
Properties | Description |
asyncIterator | Returns the default AsyncIterator for an object |
hasInstance | Determines if a constructor object recognizes an object as its instance |
isConcatSpreadable | Indicates if an object should be flattened to its array elements |
iterator | Returns the default iterator for an object |
match | Matches against a string |
matchAll | Returns an iterator that yields matches of the regular expression against a string |
replace | Replaces matched substrings of a string |
search | Returns the index within a string that matches the regular expression |
split | Splits a string at the indices that match a regular expression |
species | Creates derived objects |
toPrimitive | Converts an object to a primitive value |
toStringTag | Gives the default description of an object |
description | Returns a string containing the description of the symbol |
Example: Symbol Properties Example
const x = Symbol('hey'); // description property console.log(x.description); // hey const stringArray = ['a', 'b', 'c']; const numberArray = [1, 2, 3]; // isConcatSpreadable property numberArray[Symbol.isConcatSpreadable] = false; let result = stringArray.concat(numberArray); console.log(result); // ["a", "b", "c", [1, 2, 3]]
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.