How to create an enumeration of constants with and without explicit values in JavaScript

1 Answer

0 votes
/* 
   Title: Enumeration of Constants in JavaScript
   Example with and without explicit values
*/

// JavaScript does not have native enums, but we can simulate them using objects.

// Enum WITHOUT explicit values (simulated using auto‑increment logic)
const Color = {
  RED: 0,
  GREEN: 1,
  BLUE: 2
};

console.log("Enum without explicit values:");
console.log("RED =", Color.RED);
console.log("GREEN =", Color.GREEN);
console.log("BLUE =", Color.BLUE);

// Enum WITH explicit and mixed values
const Status = {
  OK: 1,
  WARNING: 5,
  ERROR: 6,      // manually assigned (simulating auto-increment)
  CRITICAL: 10
};

console.log("\nEnum with explicit and mixed values:");
console.log("OK =", Status.OK);
console.log("WARNING =", Status.WARNING);
console.log("ERROR =", Status.ERROR);
console.log("CRITICAL =", Status.CRITICAL);

// Using Object.freeze() to make enum immutable (recommended)
const FrozenDays = Object.freeze({
  SUNDAY: 0,
  MONDAY: 1,
  TUESDAY: 2
});

console.log("\nImmutable enum example:");
console.log("SUNDAY =", FrozenDays.SUNDAY);

// Attempt to modify (will fail silently or throw in strict mode)
FrozenDays.SUNDAY = 99;
console.log("After modification attempt, SUNDAY =", FrozenDays.SUNDAY);



/* 
run:

Enum without explicit values:
RED = 0
GREEN = 1
BLUE = 2

Enum with explicit and mixed values:
OK = 1
WARNING = 5
ERROR = 6
CRITICAL = 10

Immutable enum example:
SUNDAY = 0
After modification attempt, SUNDAY = 0

*/

 



answered Apr 25 by avibootz

Related questions

...