Using `map()` on JavaScript Enums

Sep 28, 2021

JavaScript doesn't support enums natively, but you can use POJOs to simulate vanilla JavaScript enums as shown below.

function createEnum(values) {
  const enumObject = {};
  for (const val of values) {
    enumObject[val] = val;
  }
  return Object.freeze(enumObject);
}

// { Up: 'Up', Down: 'Down', Left: 'Left', Right: 'Right' }
createEnum(['Up', 'Down', 'Left', 'Right']);

Since a JavaScript enum is just an object, you can iterate over an object using map() and Object.keys() as shown below.

// { Up: 'Up', Down: 'Down', Left: 'Left', Right: 'Right' }
const direction = createEnum(['Up', 'Down', 'Left', 'Right']);

// ['UP', 'DOWN', 'LEFT', 'RIGHT']
const uppercaseNames = Object.keys(direction).map(key => key.toUpperCase());

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!