What is the syntax to define enums in javascript?

JavascriptObject Oriented ProgrammingFront End Technology

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 }
raja
Published on 18-Sep-2019 13:54:22
Advertisements