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() { // 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();
OutputSymbol(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();
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();
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();
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();
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics
My Profile