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

What is the syntax to define enums in javascript?


Enums are not supported in JavaScript natively. We can however create Enums using Object.freeze by creating objects containing all the enumerable properties and then freezing the object so that no new enum can be added to it.

Example

const Color = {
   RED: 1,
   BLUE: 2,
   GREEN: 3,
   YELLOW: 4
};
Object.freeze(Color);
// Example usage:
let carColor = Color.BLUE;
// Trying to add new colors fails silently:
Color.WHITE = 5;
console.log(Color)

Output

{ RED: 1, BLUE: 2, GREEN: 3, YELLOW: 4 }