The Symbol.for(string) method

The Symbol object maintains a registry of the key/value pairs, where the key is the symbol description, and the value is the symbol. Whenever we create a symbol using the Symbol.for() method, it gets added to the registry and the method returns the symbol. If we try to create a symbol with a description that already exists, then the existing symbol will be retrieved. The advantage of using the Symbol.for() method instead of the Symbol() method to create symbols is that while using the Symbol.for() method, you don't have to worry about making the symbol available globally, because it's always available globally. Here is an example to demonstrate this:

let obj = {};(function(){ let s1 = Symbol("name"); obj[s1] ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.