Using symbol(), we assign value to the variable of unique type. Different variables with same data will be treated as unique data inside variables due to symbol datatype.
To create Symbol, we use Symbol() function.
// creating symbol var x = Symbol(); typeof x; // symbol
We can pass a string as its description. For example:
var x = Symbol("Welcome to Share Query"); console.log(typeof x); console.log(x); #Output symbol Symbol(Welcome to Share Query)
Access Symbol Description
Symbol value can not be used directly to the document. If we directly access a symbol value in document, it will show error.
var x = Symbol("Welcome to Share Query"); alert(x); #Output Uncaught TypeError: Cannot convert a Symbol value to a String at ....
In the above example, we have used alert() function to show the greeting value in the document. As per error, Symbol() does not allow value on document except String.
So, let us convert variable value to string first:
let greeting = Symbol("Welcome to Share Query"); alert(greeting.toString()); #Output In alert dialog box: Symbol(Welcome to Share Query)
To access the description of a Symbol function , we use the dot (.) operator followed by description keyword.
let greeting = Symbol("Welcome to Share Query"); alert(greeting.description); #Output Welcome to Share Query
Add Symbol as an Object Key
Let us check an example to understand better:
Output in Console:
In the above example, we have created a symbol data type for dept variable. While assigning value for dept in student object, we need to put dept key in square brackets in order to recognize it as symbol.
Here, we see there is no any description about symbol as we didn’t specify any description for symbol. Let us provide some description for symbol and watch it’s output again:
Output in Console:
Here we see it showing dept as a description for Symbol.
A program to retrieve object symbol value.
A symbol can not be accessed by loop (for loop).