What is JavaScript Symbol?
In JavaScript, the image function is a feature that returns a distinct symbol value each time it is invoked. Symbols in JavaScript are both immutable and unique, which makes them highly advantageous for creating property keys that can be assured to remain distinct across various objects. This functionality is commonly utilized to define non-enumerable properties within objects.
In straightforward terms, JavaScript symbols represent a novel kind of primitive data type introduced in the ES6 version of the language. This data type is on par with others such as Number, String, and Boolean. Symbols serve as unique identifiers and can be utilized in multiple contexts, including the creation of object properties.
The JavaScript Symbol is a built-in function that serves the purpose of uniquely identifying object properties.
Points to remember
- A Symbol method always return a unique value.
- A symbol value may be used as an identifier for object properties.
- Symbols are immutable, just like numbers or strings.
- Symbols cannot be typecasted to primitive data types.
Syntax
[Symbol.property](string)
Parameters
description: This is not mandatory. We have the ability to provide a string as an argument.
JavaScript Symbol Property
Here is a compilation of JavaScript Symbol properties along with their corresponding descriptions.
| Symbol.hasInstance | It is used to determine if a constructor object recognizes an object as its instance. |
|---|---|
| Symbol.isConcatSpreadable | It is used to configure if an object should be flattened to its array elements. |
| Symbol.match | It is a method to identify the matching of a regular expression against a string. |
| Symbol.prototype | It is used for produce the prototype for the symbol constructor. |
| Symbol.replace | It replace matched substring of a string. |
| Symbol.search | It returns the index within a string that matches with the regular expression. |
| Symbol.split | It splits a string at the indices that match the regular expression. |
| Symbol.toPrimitive | It is used to convert an object to its equivalent primitive value. |
| Symbol.unscopables | It is a well-known object property whose property name are excluded from with environment. |
JavaScript Symbol Methods
Here is a compilation of JavaScript Symbol Methods along with their explanations.
| Symbol.for() | It is used to search for existing symbol in a runtime-wide symbol registry with the provided key and returns if it is found. Otherwise new symbol gets created with this key. |
|---|---|
| Symbol.keyFor() | It uses the global symbol registry to look up the key for the symbol. So it doesn't work for non-global symbols. If the symbol is not global, it won't be able to find it and returns undefined. |
| Symbol.toString() | It is used to return a string representation of an object. |
Why do we use the JavaScript Symbol?
Below are several reasons for utilizing symbols in JavaScript, including:
Unique property keys
In JavaScript, symbols serve chiefly as distinct property keys within objects. Unlike strings or numbers, symbols ensure that their property keys remain unique. This feature helps to avoid naming conflicts in objects, especially in scenarios where multiple libraries or modules interact with the same object, or when augmenting native objects.
Private properties and methods
Symbols serve the purpose of establishing private properties and methods within classes or objects. In JavaScript, the uniqueness of the symbol value, coupled with the lack of exposure through any inherent methods, makes it challenging to unintentionally access or alter these properties from outside the object.
Well-known symbols
JavaScript includes a variety of pre-defined symbols that are accessible as properties of the symbol constructor. These symbols serve the purpose of tailoring the behavior of objects in particular contexts, including iteration, property retrieval, and conversion to primitive values.
Avoiding name clashes
Utilizing symbols assists in preventing unintentional naming conflicts among various components of a program that may lack awareness of one another. This approach proves especially beneficial in extensive applications or frameworks, where distinct modules or libraries could potentially engage with common objects.
To summarize, JavaScript symbols serve mainly the purpose of generating distinct property keys and establishing private members within objects. This can enhance the resilience and manageability of JavaScript code by minimizing the likelihood of accidental interactions among various components of a program.
Benefits of using the JavaScript symbol
Utilizing JavaScript symbols offers numerous advantages. Among these are:
Garbage collection
By utilizing symbols, we can prevent memory leaks, as a symbol persists in memory once it has been generated, remaining there until it is explicitly deleted, regardless of whether it is utilized anywhere else within the code.
Framework and libraries
In frameworks and libraries, we utilize symbols to establish specific behaviors or functionalities while minimizing the potential for naming collisions or unintentional alterations.
Meta programming
By utilizing symbols, we can unlock sophisticated metaprogramming strategies, which include the creation of personalized iteration behaviors, the implementation of operator overloading, or the facilitation of custom property functionalities.
Encapsulation
By utilizing symbols, it is possible to establish private properties for objects. Since symbols cannot be enumerated through for…in loops or by using Object.keys, they serve as an effective means to conceal certain properties from external access.
In conclusion, utilizing JavaScript symbols allows us to establish distinct keys, prevent naming conflicts, encapsulate properties within objects, and facilitate sophisticated meta-programming methods. This ultimately contributes to improved code clarity, modularity, and overall robustness.
How does the JavaScript Symbol work?
In JavaScript, a symbol is a primitive data type that was introduced with ES6. It is utilized to generate unique identifiers that are immutable and cannot be altered. Here is how symbols function:
Creating symbol
To begin, we must generate a symbol by utilizing the Symbol function:
const mySymbol = Symbol();
Every invocation of Symbol generates a distinct and individual Symbol value, regardless of whether the description remains identical.
const symbol1 = Symbol('foo');
const symbol2 = Symbol('foo');
console.log(symbol1 === symbol2); // false
In this illustration, symbol1 and symbol2 represent separate entities even though both share the identical description 'foo'.
Unique identifier
In JavaScript, symbols are assured to be distinct. They prove advantageous when a property key for an object is required, particularly to avoid conflicts with other properties, especially in situations where external code could engage with your objects.
Symbols as Object Properties
In JavaScript, symbols serve as keys within objects. Unlike regular keys, they are not counted in for…in loops or returned by Object.keys, which renders them advantageous for establishing hidden or private properties within objects.
const myObject = {};
const mySymbol = Symbol('mySymbol');
myObject[mySymbol] = 'Hello!';
console.log(myObject[mySymbol]); // 'Hello!'
Well-known symbols
JavaScript additionally specifies a number of intrinsic symbols that carry particular significance. These symbols can be accessed through the properties of the symbol function:
const sym = Symbol.iterator; // Symbol for the iterable protocol
Global Symbols
Symbols can be utilized across various domains through the methods Symbol.for and Symbol.keyFor:
const globalSymbol = Symbol.for('globalSymbol'); // Creates or retrieves a global symbol
console.log(Symbol.keyFor(globalSymbol)); // 'globalSymbol'
Use Cases
In JavaScript, symbols serve as a mechanism for creating distinct keys for object properties, particularly when it is essential to prevent name conflicts within libraries or frameworks. They can also be utilized for establishing internal implementation specifics that are intended to remain inaccessible from outside a module or library.
In JavaScript, symbols serve as a mechanism to generate distinct identifiers that do not appear during standard object enumerations. This characteristic renders them ideal for a range of sophisticated applications, including meta programming and the development of libraries.
Methods for JavaScript Symbols
JavaScript Symbols come with several methods, including:
For: Utilizing the for method, we can locate existing symbols.
keyFor: This method enables us to retrieve a shared symbol key from the global symbol registry.
toSource: This method allows us to obtain a string representation that includes the source code of the symbol object.
toString: This method is utilized to return a string that encapsulates the description of the symbol.
valueOf: Utilizing this method, we are able to retrieve the primitive value associated with the Symbol object.
JavaScript Symbol Methods
Here is a compilation of JavaScript Symbol methods along with their respective explanations.
Symbol.for
This function is utilized to look up an existing symbol within a runtime-wide symbol registry using the specified key. If the symbol is located, it will return the found symbol. If not, a new symbol will be generated using the provided key.
Symbol.keyFor
It utilizes the global symbol registry to retrieve the key associated with the symbol. Consequently, this approach does not function for symbols that are not global. If the symbol in question is not global, the lookup will fail, resulting in an undefined value being returned.
Symbol.toString
It is utilized to provide a string representation of an object.
Example 1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>What are JavaScript symbols?</title>
</head>
<body>
<h3>What are JavaScript symbols?</h3>
<pre id="code"></pre>
<script>
const code= document.getElementById("code");
const mySymbol = Symbol("myProperty");
const obj= {
[mySymbol]: "This is a hidden property",
otherProperty: "Visible property",
};
console.log(obj.otherProperty);
console.log(obj[mySymbol]);
code.innerHTML = `output: ${obj.otherProperty} <br> output: ${obj[mySymbol]}`;
</script>
</body>
</html>
Output:
Example 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>What are JavaScript symbols?</h3>
<pre id="code"></pre>
<script>
const code = document.getElementById("code");
const arr = [1, 2, 3];
console.log(arr[Symbol.iterator]);
code.innerHTML = `output: ${arr[Symbol.iterator]}`;
</script>
</body>
</html>
Output:
Example 3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>what are JavaScript symbols?</h3>
<pre id="code"></pre>
<script>
const code= document.getElementById("code");
const firstName = Symbol("fisrtName");
const lastName = Symbol("lastName");
const person = {
[firstName]: "Rohit",
[lastName]: "Kumar",
};
console.log(person[firstName]);
console.log(person[lastName]);
console.log(Object.getOwnPropertySymbols(person));
code.innerHTML =`output: ${person[firstName]}; ${person[lastName]};`;
</script>
</body>
</html>
Output: