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

Explain Enumerated Types in JavaScript.


JavaScript doesn’t support Enums out of the box. The only way to have enums in javaScript is to implement them using objects.

Following is the code showing enumerated types in JavaScript −

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: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Enumerated Types in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to get the color values</h3>
<script>
   let resEle = document.querySelector(".result");
   let color = {
      orange: 1,
      red: 2,
      green: 3,
      blue: 4,
      pink: 5,
   };
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML += "color.orange = " + color.orange + "<br>";
      resEle.innerHTML += "color.red = " + color.red + "<br>";
      resEle.innerHTML += "color.green = " + color.green + "<br>";
      resEle.innerHTML += "color.blue = " + color.blue + "<br>";
      resEle.innerHTML += "color.pink = " + color.pink + "<br>";
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

Explain Enumerated Types in JavaScript.

On clicking the ‘CLICK HERE’ button −

Explain Enumerated Types in JavaScript.