JavaScript Symbol() Constructor
Last Updated :
07 Aug, 2023
The Symbol() constructor is used to create a new symbol. The Symbol() constructor returns a value of the type of symbol with static properties. Every time we call the constructor a unique symbol is created. A Symbol constructor is a primitive data type having no object or no methods which are generally used as an identifier.
Syntax:
Symbol(str)
Arguments: The only argument is an optional string that is used for debugging but not to access the symbol. It means every time we call Symbol() constructor a unique symbol is created.
Return value: The Symbol() constructor returns a value of the type of symbol. And every time a unique symbol is returned.
Example 1: Below is the example of the Symbol() constructor.
Javascript
function func() {
const sym1 = Symbol();
const sym2 = Symbol(9);
const sym3 = Symbol( "GFG" );
console.log(sym2.toString());
console.log( typeof sym1);
console.log(sym3 == "GFG" );
}
func();
|
Output
Symbol(9)
symbol
false
Example 2: In this example, the constructor creates a new primitive symbol const sym1 = Symbol();
Javascript
function func() {
const sym1 = Symbol();
console.log(sym1);
}
func();
|
Example 3: In this example, the constructor creates a new primitive symbol with an argument const sym2 = Symbol(9);
Javascript
function func() {
const sym2 = Symbol(9);
console.log(sym2.toString());
}
func();
|
Example 4: In this example, the constructor creates a new primitive symbol with a string argument const sym3 = Symbol(“GFG”);
Javascript
function func() {
const sym3 = Symbol( "GFG" );
console.log(sym3);
}
func();
|
Example 5: In this example, we compare the return symbol with the string and return true if both are equal, otherwise, it returns false. Since the Symbol() constructor returns only a symbol, its output is false, console.log(sym3 == “GFG”);.
Javascript
function func() {
const sym3 = Symbol( "GFG" );
console.log(sym3 == "GFG" );
}
func();
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...