JS: Enum: Creating enum functionality in JS | JavaScript

Enum in JavaScript

JavaScript has no default support of enum unlike other progrmming languages like c++, c# etc. Enum functionality can be achieved using Object.freeze static function in JavaScript.

Enum flags in JavaScript

var Fruits = Object.freeze({"Mango":1, "Orange":2, "Apple":3, "Pineapple" :4, "Grape": 5, "Banana": 6}); var f1 = Fruits.Orange; var f2 = 5;// Grape if(f1 === Fruits.Orange) console.log('Chose Orange'); if(f2 === Fruits.Grape) //f2 === 5 and Fruits.Grape === 5 console.log('also Grape'); Chose Orange also Grape

Iterating Enum in loops

var Fruits = Object.freeze({"Mango":1, "Orange":2, "Apple":3, "Pineapple" :4, "Grape": 5, "Banana": 6}); for(var f in Fruits) console.log(Fruits[f], f) 1 Mango 2 Orange 3 Apple 4 Pineapple 5 Grape 6 Banana

Fruits is itereted just like any other Object. The difference is that Fruits properties have been made readonly using Object.freeze function.

Using Enum as Flags

Using enum to allow multiple values in a single variable but the upcoming value must double the previous value

var Fruits = Object.freeze({"Mango":1, "Orange":2, "Apple":4, "Pineapple" :8, "Grape": 16, "Banana": 32, "Cherry": 64}); var yellowFruits = Fruits.Mango | Fruits.Banana; if(yellowFruits & Fruits.Mango) console.log('Mango is a yellow fruit'); Mango is a yellow fruit

Mango and Banana are assigned to yellowFruits using | operator.

Similarly, we may also assign

var Fruits = Object.freeze({"Mango":1, "Orange":2, "Apple":4, "Pineapple" :8, "Grape": 16, "Banana": 32, "Cherry": 64}); var yellowFruits = Fruits.Mango | Fruits.Banana; var redFruits = Fruits.Apple | Fruits.Cherry; if(yellowFruits & Fruits.Mango) console.log('Mango is a yellow fruit'); else console.log('Mango is not a yellow fruit'); if(redFruits & Fruits.Mango) console.log('Mango is a red fruit'); else console.log('Mango is not a red fruit'); Mango is a yellow fruit Mango is not a red fruit