Challenge - 5 Problems
Numeric Enum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of numeric enum auto-increment
What is the output of the following TypeScript code when compiled and run in JavaScript?
Typescript
enum Direction {
Up,
Down,
Left,
Right
}
console.log(Direction.Up, Direction.Down, Direction.Left, Direction.Right);Attempts:
2 left
💡 Hint
Numeric enums start numbering from 0 by default unless specified.
✗ Incorrect
By default, numeric enums start at 0 and increment by 1 for each member. So Up is 0, Down is 1, Left is 2, and Right is 3.
❓ Predict Output
intermediate2:00remaining
Custom starting value in numeric enum
What will this TypeScript code output when run?
Typescript
enum Status {
Ready = 5,
Waiting,
Complete
}
console.log(Status.Ready, Status.Waiting, Status.Complete);Attempts:
2 left
💡 Hint
When you assign a number to the first member, the next members increment from that number.
✗ Incorrect
The first member Ready is set to 5, so Waiting becomes 6 and Complete becomes 7 automatically.
🔧 Debug
advanced2:00remaining
Why does this enum cause an error?
This TypeScript enum code causes a compilation error. What is the reason?
Typescript
enum Colors {
Red = 1,
Green = Red + "2",
Blue
}Attempts:
2 left
💡 Hint
Enum values must be constant expressions for numeric enums.
✗ Incorrect
Numeric enum members must be initialized with constant values or expressions that resolve to constants. Using string concatenation results in a non-constant expression, causing an error.
❓ Predict Output
advanced2:00remaining
Reverse mapping of numeric enums
What is the output of this TypeScript code?
Typescript
enum Weekday {
Monday = 1,
Tuesday,
Wednesday
}
console.log(Weekday[2]);Attempts:
2 left
💡 Hint
Numeric enums create a reverse mapping from value to name.
✗ Incorrect
Numeric enums in TypeScript create a reverse mapping, so Weekday[2] returns the name of the member with value 2, which is "Tuesday".
🧠 Conceptual
expert2:00remaining
Number of enum members after compilation
Given this TypeScript enum, how many keys will the compiled JavaScript object have?
Typescript
enum Levels {
Low = 1,
Medium = 3,
High
}Attempts:
2 left
💡 Hint
Remember that numeric enums create both forward and reverse mappings for each member.
✗ Incorrect
Each enum member creates two keys: one for the name to value and one for the value to name. Since High is 4 (3 + 1), there are 3 members, so 3 * 2 = 6 keys.