DEV Community

Cover image for What is Symbol.for in JavaScript?
Augustine
Augustine

Posted on

What is Symbol.for in JavaScript?

Symbol.for is a built-in method of Symbol's in JavaScript. What is it for and what is the difference between Symbol and Symbol.for?

Symbol.for

Like Symbol, Symbol.for always returns a Symbol for a given key as well. What is unlike Symbol is Symbol.for will return the same Symbol if the key was registered once. When Symbol.for(key) is called for the first, a Symbol with the given key will be generated and stored in the global Symbol registry. It becomes a global Symbol.

Here is the difference between both.

With Symbol

let symbol1 = Symbol('foo');
let symbol2 = Symbol('foo');
symbol1 === symbol2   // false
Enter fullscreen mode Exit fullscreen mode

But with Symbol.for

let symbol1 = Symbol.for('foo');
let symbol2 = Symbol.for('foo');
symbol1 === symbol2   // true
Enter fullscreen mode Exit fullscreen mode

Here is the explanation.

// the symbol `foo` doesn't exist, a symbol is created.
let symbol1 = Symbol.for('foo');
// the symbol `foo` has been created and registered, so return it.
let symbol2 = Symbol.for('foo');
// both are the same symbol
symbol1 === symbol2 // true
Enter fullscreen mode Exit fullscreen mode

Symbol.keyFor

This is a reverse call of Symbol.for. When Symbol.for(key) creates a global Symbol, Symbol.keyFor(key) returns the key name of this Symbol.

let symbol1 = Symbol.for('foo');
Symbol.keyFor(symbol1);  // 'foo'
Enter fullscreen mode Exit fullscreen mode

Symbol.keyFor don't return the name of a local Symbol. It returns undefined instead.

let globalSymbol = Symbol.for('foo');
let localSymbol = Symbol('foo');
Symbol.keyFor(globalSymbol);  // 'foo'
Symbol.keyFor(localSymbol);  // undefined
Enter fullscreen mode Exit fullscreen mode

In conclusion

A Symbol is guaranteed to be unique. It is often used to be a property key of an object so that the properties will not corrupt each other. In modern libraries/frameworks, such as React, node-Redis, and so on, Symbol has been used a lot to identify the different properties and types. Most of the browsers have supported it, except IE. If you want to know if it is available on your browsers, you can check it on the caniuse website.

Thank you for reading.

Top comments (0)