Numeric enum
- TypeScript course
- Beginner
- Lesson 20/89
- 4 min
Learn to define numeric enums.
Numeric enum
An enum is a set of named constants. In a numeric enum, members start at 0 by default and auto-increment. You reach each member with dot notation and its value is a number.
enum Yon { Kuzey, Guney, Dogu, Bati }
// Kuzey=0, Guney=1, Dogu=2, Bati=3
console.log(Yon.Guney); // 1An enum is the readable way to group related constants under one name.
Start value and explicit assignment
An enum starts at 0 by default, but if you assign a value to the first member, the following members increment from there. You can also assign a number explicitly to any member.
enum Kod { Hata = 100, Tamam, Devam }
// Hata=100, Tamam=101, Devam=102Explicit assignment is useful for defining meaningful code numbers.
Practice Define the season constant
Define a const named Mevsim mapping Ilkbahar, Yaz, Sonbahar, Kis to 0, 1, 2, 3 in order (numeric enum behavior). Print the value of Mevsim.Yaz with console.log.
Starter code
// Mevsim adında bir const tanımla
// Ilkbahar, Yaz, Sonbahar, Kis üyelerini 0, 1, 2, 3 ile eşle
// Mevsim.Yaz değerini yazdırSample solution
const Mevsim = { Ilkbahar: 0, Yaz: 1, Sonbahar: 2, Kis: 3 };
console.log(Mevsim.Yaz);Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>enum Yon { Kuzey, Guney, Dogu }</code>, what is <code>Yon.Guney</code>?
- 2
- "Guney"
- 1 Correct answer
- 0
Explanation: A numeric enum starts at 0 and auto-increments; <code>Kuzey=0</code>, <code>Guney=1</code>, <code>Dogu=2</code>.
2 Set the start value to 10
enum Seviye { Dusuk = ____, Orta, Yuksek }
enum Seviye { Dusuk = 10, Orta, Yuksek }
Explanation: Setting <code>Dusuk = 10</code> makes <code>Orta=11</code> and <code>Yuksek=12</code>; since a start value of 10 was requested, the answer is <code>10</code>.
3 Numeric enum concepts
| Term | Meaning |
|---|---|
enum Renk { Kirmizi, Yesil } |
Auto-incremented values starting at 0 |
enum Kod { A = 5, B } |
Values starting at 5 |
enum Yon { Kuzey = 0, Guney = 1 } |
Explicitly set values |
Numeric enum |
Named number constants |