Understanding Symbol() in JavaScript
Below we will unpack how Symbol() is best utilized. Referencing Colt Steel’s tutorial on JavaScript Symbol() using ES6.
Symbol()-special unique value behind. Not the same. Won’t print out differently.
sym1 returns Symbol()
sym2 returns Symbol()
sym1 === sym2 returns false
Use Symbols() as an identifier for object properties (the data type’s only purpose). Is unique and a primitive data type. Returns a value of type symbol, has static properties exposing several members of built-in objects, has static methods exposing the global symbol register while resembling a built-in object class. So then, it cannot be implemented as a constructor since it does not support the syntax “new Symbol()”. (Resource: MDN on Symbol())
Object literal here with const idSym = Symbol(‘id’); won’t work. We will need to add brackets to invoke the Symbol() otherwise it will return a string.
//EXAMPLES BY COLT STEELE
//Object literal using Symbol()
const idSym = Symbol('id');
let user = {
id : 9451,name : 'James',city : 'Los Angeles', age : 59,idSym : 94530203
}//call 'user' with returns //won't be the best option
user
{id: 9451, name: 'James', city: 'Los Angeles', age: 59, idSym: 94530203}
age: 59
city: "Los Angeles"
id: 9451
idSym: 94530203 //string <-- the problem!!
name: "James"//best option with implementing Symbol() in user's objectconst idSym = Symbol('id');
let user = {
id : 9451,name : 'James',city : 'Los Angeles', age : 59,[idSym] : 94530203 //add those brackets to return Symbol()
}
[[Prototype]]: Object//user's return using [idSym] syntax
user
{id: 9451, name: 'James', city: 'Los Angeles', age: 59, Symbol(id): 94530203}
age: 59
city: "Los Angeles"
id: 9451
name: "James"
Symbol(id): 94530203 //Symbol(id), not a string
[[Prototype]]: Object
make a global symbol with .for, won’t be a unique descriptor, in this given method. global Symbol() space.
The Symbol.keyFor(sym) method retrieves a shared symbol key from the global symbol registry for the given symbol. Resource
//EXAMPLE BY COLT STEELE
const sym1 = Symbol.for('cat')
//Symbol.for('cat') //are keys
//versus properties without the .for in Symbol('cat')
const sym2 = Symbol.for('cat')
sym1 = sym2 return true
Symbol() to represent concepts and ideas, something that is unique.
//EXAMPLE BY COLT STEELE
const BLUE = 'blue';
const cat = 'blue';function getThreatLevel(color){ switch(color) {
case BLUE:
return 'low';
default:
console.log("I DON'T KNOW THAT COLOR!");
}
};
getThreatLevel(BLUE) => 'low'
getThreatLevel(cat) => 'low'//using Symbol()
const BLUE = Symbol('blue');
getThreatLevel(BLUE) => 'low'
getThreatLevel(cat) => I DON'T KNOW THAT COLOR!
use Symbol() as keys preventing name clashes/collisions
Thank you for reading! Happy Coding.
Resources
- Griffith, Steve. “Intro to JavaScript Symbols”
- Steele, Colt. “The Complete Guide to JS Symbols ES6”
- MDN Web Docs: Symbol
- MDN Web Docs: Symbol.for()