Challenge - 5 Problems
Enum Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of accessing enum members by name and value?
Consider the following TypeScript enum and code snippet. What will be printed to the console?
Typescript
enum Direction {
Up = 1,
Down,
Left,
Right
}
console.log(Direction.Up);
console.log(Direction[2]);Attempts:
2 left
💡 Hint
Remember that enums in TypeScript can be accessed both by member name and by numeric value.
✗ Incorrect
Direction.Up is assigned 1 explicitly, so console.log(Direction.Up) prints 1. Direction[2] accesses the enum member with value 2, which is 'Down'. So the output is '1' and then 'Down'.
❓ Predict Output
intermediate2:00remaining
What happens when accessing a non-existent enum member by value?
Given this enum and code, what will be the output?
Typescript
enum Status {
Active = 1,
Inactive = 3,
Pending = 5
}
console.log(Status[2]);Attempts:
2 left
💡 Hint
Check if the enum has a member with the value 2.
✗ Incorrect
The enum Status has members with values 1, 3, and 5. There is no member with value 2, so Status[2] returns undefined.
🔧 Debug
advanced2:00remaining
Why does this enum member access cause a runtime error?
Examine the code below. Why does accessing Color['Blue'] cause a runtime error?
Typescript
enum Color {
Red = 'RED',
Green = 'GREEN'
}
console.log(Color['Blue']);Attempts:
2 left
💡 Hint
Check how string enums behave when accessed by keys that don't exist.
✗ Incorrect
Accessing Color['Blue'] returns undefined because 'Blue' is not a member of the enum. This does not cause a runtime error; it just returns undefined.
❓ Predict Output
advanced2:00remaining
What is the output when accessing numeric enum members with computed values?
Look at this enum and code. What will be the output?
Typescript
enum FileAccess {
None,
Read = 1 << 1,
Write = 1 << 2,
ReadWrite = Read | Write,
G = '123'.length
}
console.log(FileAccess.ReadWrite);
console.log(FileAccess[3]);
console.log(FileAccess.G);Attempts:
2 left
💡 Hint
Calculate the bitwise OR and the length of the string.
✗ Incorrect
Read is 2 (1 << 1), Write is 4 (1 << 2), so ReadWrite is 6 (2 | 4). FileAccess[3] is undefined because 3 is not assigned to any member. G is 3 ('123'.length). FileAccess.G is 3.
❓ Predict Output
expert3:00remaining
What is the output of this mixed enum member access?
Analyze the following enum and code. What will be printed?
Typescript
enum Mixed {
A = 1,
B,
C = 'C',
D = 5
}
console.log(Mixed.A);
console.log(Mixed.B);
console.log(Mixed.C);
console.log(Mixed[2]);
console.log(Mixed[5]);
console.log(Mixed['C']);Attempts:
2 left
💡 Hint
Remember that string enum members do not create reverse mappings.
✗ Incorrect
A is 1, B is 2 (auto increment). C is a string 'C'. D is 5. Mixed[2] is 'B' (reverse mapping). Mixed[5] is 'D' (reverse mapping). Mixed['C'] is 'C' (direct property access).