Enums

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Aug 19, 2022Updated Jul 1, 2024
Contribute to Docs

JavaScript has no support for a native enum type, but it is possible to define enums using Objects. In general, enums are a type that can hold a finite number of defined values. The values in enums are not mutable.

Implementing an Enum in JavaScript

A way to implement an enum in JavaScript by creating an Object of key/value pairs and using the Object.freeze() function to make it immutable:

const directions = Object.freeze({
north: 0,
south: 1,
east: 2,
west: 3
});

The enum can be used as follows:

let d = directions.north;

All possible enum values can be listed as follows:

Object.keys(directions).forEach((direction) =>
console.log('direction:', direction)
);

This would produce the output:

direction: north
direction: south
direction: east
direction: west

Codebyte Example

This codebyte example demonstrates the creation of an enum using Object.freeze(), how to use the enum values, and list all possible enum values:

Code
Output
Loading...

All contributors

Looking to contribute?

Learn JavaScript on Codecademy