„Hacking” in JS: Enums

devobry

DevObry

Posted on August 5, 2021

„Hacking” in JS: Enums

Hello, it’s 2021 why I should use „fake” enums in JS while can use Typescript to provide serious enum logic?

Yeah, we don’t live in the perfect life and sometimes we have to stick to the JS for some reason. Even with JS, we should try to write as clean code as we can. Enums are very helpful when we have to define a variable with a definite number of fixed values. Then, we will obtain a boost to readability. For example:

let color = "red"

switch (color) {
 case "blue":
  console.log("It's blue")
  break
 case "red":
  console.log("It's red")
  break
 case "purple":
  console.log("It's purple")
  break
}
Enter fullscreen mode Exit fullscreen mode

With some useful knowledge we can transform it into much cleaner piece of code :

const colors = {
 BLUE: "blue",
 RED: "red",
 PURPLE: "purple"
}
Object.freeze(colors)

let color = colors.PURPLE
switch (color) {
 case colors.BLUE:
  console.log("It's blue")
  break
 case colors.RED:
  console.log("It's red")
  break
 case colors.PURPLE:
  console.log("It's purple")
  break
}
Enter fullscreen mode Exit fullscreen mode

Object.freeze + const = powerful duo to make a JS enum!

Object.freeze - this method freezes our object. This is the most helpful method to obtain enum in JS. Freezing prevents changing properties and in the enum that is our goal. More on this topic here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

Const - It provides that our variable won’t be overridden.

I think enums are quite useful and using them provides much more readability in our code.
JS code is provided here:
https://jsfiddle.net/x79g6zuq/8/

💖 💪 🙅 🚩
devobry
DevObry

Posted on August 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related