Working with the symbol primitive data type in JavaScript? Here’s how to check if you have a symbol or some other type of data.
“The data type symbol is a primitive data type. The
Symbol()
function returns a value of type symbol.” — _MDN Docs
One of the less common primitives, symbols are used as object properties and other times that unique values are required.
_“A value having the data type Symbol can be referred to as a ‘Symbol value.’ [A symbol is] an anonymous, unique value. A symbol may be used as an object property.” — _MDN Docs
The advantage of a symbol as an object property is that it won’t conflict with any other symbol; each one is unique.
“Note that
Symbol("foo")
does not coerce the string"foo"
into a symbol. It creates a new symbol each time.” — MDN Docs
You can create a global symbol, which would let you reuse symbols, by using a method on the global Symbol
object called Symbol.for()
.
“The Symbol.for(key) method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.” — MDN Docs
A symbol created with Symbol.for()
will be stored as a global symbol, meaning you can reuse it.
typeof
When trying to check the type of a variable to see if it contains a symbol, you can use the typeof
keyword.
#javascript #programming #es6 #web-development #developer