Enums
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:
Contribute to Docs
- 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.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours