BeginnerCoder

Lesson 9 — Enums

Named constants

An enum groups related constants under readable names. By default the members are numbered from 0: in enum Size { S, M, L }, Size.M is 1. Number enums also have a reverse mapping — Size[1] gives back the name "M".

enum Size { S, M, L }
const pick = Size.L;     // 2
console.log(Size[pick]); // L

Why it matters: Direction.Left is clearer and safer than a magic number 2 scattered around your code.

Want it another way?
Task

Log the number stored in Direction.Left, then the name for the number 1. Expect 2, then Down.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.