Ad space (banner)
🟨JavaScript Lessons
Lesson 42 / 69

The Basics of Enums (Enumerated Types)

In this lesson you'll learn how to reproduce an Enum (enumerated type) in JavaScript so you can safely handle a fixed set of choices. This is for people searching "JavaScript how to write an Enum" or "JavaScript Object.freeze usage."

JavaScript doesn't have a dedicated Enum syntax, but you can reproduce an "enumerated type" representing a fixed set of choices by using Object.freeze() to create an object that can't be modified. It's used when you want to limit a value's kind ahead of time, like "a traffic light only has red, blue, and yellow." Using named constants communicates intent more clearly than writing strings or numbers directly all over your code (something called a "magic number").

The sample code freezes an object called Color with Object.freeze(), giving it just three choices: RED, GREEN, and BLUE. You can pull out a value with Color.RED, and you can also get all the choices as an array with Object.values(Color).

A common beginner stumbling block is building an Enum as a plain, ordinary object without Object.freeze(), which allows its values to be changed later. To protect the intent of a "fixed set of choices," you must always freeze it. This also prevents typos, making it safer than writing strings directly all over the place.

In real development, this idea is used for handling values that have "only a fixed set of kinds," like an order's status (processing, shipped, complete) or a user's permission level. In a language called TypeScript, Enum is provided as a standard feature, making it another option worth knowing about if you want more rigorous type safety.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)