What Are Symbols in JavaScript
Code Playground is only enabled on larger screen sizes.
We just mentioned that the property values can be any data types you want, but what about the property names?
Recall that when we were using the square bracket syntax, the property names were placed inside quotation marks.
let obj = {
firstName: "John",
lastName: "Doe",
age: 25,
};
console.log(obj["firstName"]); // -> John
console.log(obj["lastName"]); // -> Doe
console.log(obj["age"]); // -> 25Yes, the property names are, in fact, strings.
In JavaScript, the object keys are either strings or symbols. Other data types will be automatically converted into strings.
Symbol, on the other hand, is another primitive data type designed to create property names. It is created with the Symbol() function.
let id = Symbol("id"); // The string "id" is the symbol descriptionAnd then, you can use this id as the object key.
let id = Symbol("id");
let obj = {
[id]: 12345,
firstName: "John",
lastName: "Doe",
age: 25,
};
console.log(obj); // -> { firstName: 'John', lastName: 'Doe', age: 25, [Symbol(id)]: 12345 }The id must be wrapped inside a pair of square brackets, or JavaScript will assume it is a plain string.
To extract the property with the symbol name, you also must use the square bracket syntax:
let id = Symbol("id");
let obj = {
[id]: 12345,
firstName: "John",
lastName: "Doe",
age: 25,
};
console.log(obj[id]); // -> 12345Do not add quotes (obj["id"]) or use the dot operator (obj.id) here, as both syntax will let JavaScript assume id is a string.
So, what exactly is the point of using a symbol? Seems like it works the same as a regular, string-based property name.
A symbol is a value guaranteed to be unique.
For example, you can create two symbols with the same name, but when you equate them, JavaScript will tell you they are not the same:
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 === id2); // -> falseSymbols are often used to hide properties. Properties defined with a symbol will be skipped in the for...in loop:
let id = Symbol("id");
let obj = {
[id]: 12345,
firstName: "John",
lastName: "Doe",
age: 25,
};
for (let key in obj) {
console.log("Key: " + key);
console.log("Value: " + obj[key]);
}Key: firstName
Value: John
Key: lastName
Value: Doe
Key: age
Value: 25console.log("Hello, World!");