What are JavaScript symbols?


A symbol in JavaScript is a primitive data type, introduced in ES6 version update, that represents an immutable and unique identifier. Unlike other primitive types like strings, booleans, numbers, etc, symbols are guaranteed to be unique. This implies that even if two symbols have the same content, they are going to be distinct (separate) entities and not equal to each other. Symbols are primarily used to avoid naming conflicts when adding properties to objects. In this Tutorial, we will learn about symbols in JavaScript. Along with that we will also learn how we can use them to add properties in objects without the risk of naming collisions.

There are 2 ways to create a symbol in JavaScript −

  • Creating Symbols with Symbol() method

const mySymbol = Symbol();
  • Creating Symbols with Symbol.for() method

const mySymbol1 = Symbol.for('myKey');

Let’s understand the above concept with the help of some examples.

Example 1

In the following example we are going to use symbols as property names in objects to add non−iterable properties. These properties cannot be accessed in a for loop, such as mySymbol, without the risk any collisions of naming. Non−iterable, or non−enumerable, properties are not visible during iteration.

Filename: index.html

<html lang="en">
<head>
   <title>What are JavaScript symbols?</title>
</head>
<body>
   <h3>What are JavaScript symbols?</h3>
   <pre id="code"></pre>

   <script>
      const code = document.getElementById("code");

      const mySymbol = Symbol("myProperty");

      const obj = {
         [mySymbol]: "This is a hidden property",
         otherProperty: "Visible property",
      };

      console.log(obj.otherProperty); // Output: Visible property
      console.log(obj[mySymbol]); // Output: This is a hidden property

      code.innerHTML = `output: ${obj.otherProperty} <br> output: ${obj[mySymbol]}`;
   </script>
</body>
</html>

Output

Example 2

In this example, we will use the built−in javascript symbols which can be accessed using static properties on the Symbol object, such as Symbol.iterator for defining default iterable (accessible in a for loop) properties of objects or Symbol.toStringTag for customizing the toString() behavior of an object.

Filename: index.html

<html lang="en">
<head>
   <title>What are JavaScript symbols?</title>
</head>
<body>
   <h3>What are JavaScript symbols?</h3>
   <pre id="code"></pre>

   <script>
      const code = document.getElementById("code");

      const arr = [1, 2, 3];

      console.log(arr[Symbol.iterator]); // Output: [Function: values]

      code.innerHTML = `output: ${arr[Symbol.iterator]}`;
   </script>
</body>
</html>

Output

Example 3

In this example, we will create symbols firstName and lastName to represent the properties of a person object. By using symbols as property names, we will ensure that these properties are unique and hence avoids property name collision.

Filename: index.html

<html lang="en">
<head>
   <title>What are JavaScript symbols?</title>
</head>
<body>
   <h3>What are JavaScript symbols?</h3>
   <pre id="code"></pre>

   <script>
      const code = document.getElementById("code");

      const firstName = Symbol("firstName");
      const lastName = Symbol("lastName");

      const person = {
         [firstName]: "John",
         [lastName]: "Doe",
      };

      console.log(person[firstName]); // Output: John
      console.log(person[lastName]); // Output: Doe

      console.log(Object.getOwnPropertySymbols(person)); // Output: [Symbol(firstName), Symbol(lastName)]

      code.innerHTML = `output: ${person[firstName]}; ${
         person[lastName]
      };`;
   </script>
</body>
</html>

Output

Conclusion

JavaScript symbols are a unique primitive data type that was introduced in ES6. It provides a great way to create unique and immutable identifiers. These Symbols are widely used to add non−enumerable, or non−iterable, properties to objects without the risk of naming collisions. We learned the concept of symbols in JavaScript and saw some examples explaining the same.

Updated on: 16-Aug-2023

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements