Computer >> Computer tutorials >  >> Programming >> Javascript

What are JavaScript symbols?


The symbol data type is a primitive data type. They were introduced in ES6 and are completely unique and created using the Symbol() factory function which returns the Symbol.

Following is the code for JavaScript symbols −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18;
      color: blueviolet;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript symbols</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to display and compare symbols</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let sym1 = Symbol("test");
   let sym2 = Symbol("test");
   BtnEle.addEventListener("click", () => {
      console.log(sym1);
      console.log(sym2);
      if (sym1 !== sym2) {
         resEle.innerHTML = "The symbols are not equal";
      }
   });
</script>
</body>
</html>

Output

What are JavaScript symbols?

On clicking the ‘CLICK HERE’ button and inspecting the output in console −

What are JavaScript symbols?