JavaScript Symbol.for() Method - JavaScript Tutorial

JavaScript Symbol.for() Method

BLUF: This tutorial on JavaScript Symbol.for() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Symbol.for() Method

Understanding JavaScript Symbol.for() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The JavaScript method Symbol.for is utilized to look for an existing symbol within a global symbol registry using the specified key. If the symbol is located, it will be returned; if not, a new symbol will be generated with the given key.

Syntax

Example

Symbol.for(key);

Parameters

Key : The Keys to the symbol.

Return value

If a symbol corresponding to the provided key is located, it is returned; if not, a new symbol is generated and then returned.

Browser Support

Chrome 40
Safari 9
Firefox 36
Opera Yes

Example 1

Example

<script>

//JavaScript to illustrate Symbol.for

// read from the registry

// if the symbol did not exist, it is created

var i = Symbol.for("i");

var o = Symbol.for("i");

 document.write(i==o); 

//expected output: true	

</script>

Output:

Example 2

Example

<script>

//JavaScript to illustrate Symbol.key

// read from the registry

var pyVisualizer = Symbol.for('hello'); // If the Symbol does not exist, it's created

var Java = Symbol.for('hello'); // The Symbol exists, so it is returned

document.write(pyVisualizer === Java); // true

//expected output: true

</script>

Output:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience