Enums
Anonymous contributor
Anonymous contributor1 total contribution
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 Object
s. 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: northdirection: southdirection: eastdirection: 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:
All contributors
- Anonymous contributorAnonymous contributor1 total contribution
- StevenSwiniarski474 total contributions
- Anonymous contributor
- StevenSwiniarski
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.