Open In App

JavaScript Symbol() Constructor

Last Updated : 07 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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() {
    // symbol without any parameter
    const sym1 = Symbol();
 
    // symbol with parameter
    const sym2 = Symbol(9);
 
    // symbol with string
    const sym3 = Symbol("GFG");
 
    console.log(sym2.toString());
 
    // Type of symbol 1
    console.log(typeof sym1);
 
    // Check symbol is equal to "GFG" or not
    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() {
    // symbol without any parameter
    const sym1 = Symbol();
 
    console.log(sym1);
}
func();


Output

Symbol()

Example 3: In this example, the constructor creates a new primitive symbol with an argument const sym2 = Symbol(9);

Javascript




function func() {
    // symbol with a parameter
    const sym2 = Symbol(9);
 
    console.log(sym2.toString());
}
func();


Output

Symbol(9)

Example 4: In this example, the constructor creates a new primitive symbol with a string argument const sym3 = Symbol(“GFG”);

Javascript




function func() {
    // symbol without a string parameter
    const sym3 = Symbol("GFG");
 
    console.log(sym3);
}
func();


Output

Symbol(GFG)

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() {
 
    // symbol with string
    const sym3 = Symbol("GFG");
 
    // Check symbol is equal to "GFG" or not
    console.log(sym3 == "GFG");
}
func();


Output

false



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads