Symbol in JavaScript a primitive data type

Symbol in JavaScript a primitive data type

Written by Rahul on Nov 29th, 2021 Views Report Post

It is a primitive data type along with string, number, boolean, null and undefined. To create a new primitive symbol, you define it with the following syntax.

let mySymbol = Symbol(); 

You can pass a parameter to Symbol(), and that is used as the symbol description, useful just for debugging purposes.

let mySecondSymbol = Symbol('orange'); 

They are unique, and every time you invoke Symbol(), you get a new and unique symbol that is guaranteed to be different from all other symbols.

Symbol() === Symbol() // false
Symbol('orange') === Symbol('orange') // false

Even though every symbol gives a unique value we can't view them by logging.

console.log(Symbol()); // Symbol()
console.log(Symbol('orange')); // Symbol(orange)

It won't be enumerated in for...in loops, and are ignored by function such as JSON.stringify(), Object.keys() and Object.getOwnProperty. This makes them ideal for properties that you don't want to be included when serializing an object.

const user = {}; 
const email = Symbol(); 

user.name = 'Rahul'; 
user.age = 16; 
user[email] = '[email protected]'; 

Object.keys(user); 
// [ "name", "age" ]

JSON.stringify(user); 
.. {"name":"Rahul","age":"16"}

Let's say you create a user object as shown above and have an object like, {name: "Rahul", age: 16, Symbol(): "[email protected]"}

What are the ways you can retrieve the value "[email protected]" from the user object?

Thank you for Reading⚡

Comments (0)