Iterating Over Enum Members
You'll learn how to loop through enum keys and values, understanding the quirky differences between numeric and string enums.
The Core Idea
Enums generate real JavaScript objects at runtime, which means you can iterate over them using standard Object methods. However, numeric enums behave differently than string enums when you try to loop through their members—numeric enums store both forward mappings (name → value) and reverse mappings (value → name), while string enums only store forward mappings.
Numeric Enums: Dealing with Reverse Mappings
When you iterate over a numeric enum, you'll get both keys and values because of reverse mapping:
enum Status {
Pending,
Active,
Completed
}
// Loop through all keys
Object.keys(Status).forEach(key => {
console.log(key); // Logs: "0", "1", "2", "Pending", "Active", "Completed"
});
// To get only the names, filter out numeric keys
const names = Object.keys(Status).filter(key => isNaN(Number(key)));
console.log(names); // ["Pending", "Active", "Completed"]
String Enums: Straightforward Iteration
String enums are simpler—they only have forward mappings:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
Object.keys(Color).forEach(key => {
console.log(key); // Logs: "Red", "Green", "Blue"
});
// Access values easily
Object.values(Color).forEach(value => {
console.log(value); // Logs: "RED", "GREEN", "BLUE"
});
Key Takeaway: Numeric enums require filtering to avoid reverse-mapped entries when iterating, while string enums iterate cleanly through their keys and values without extra ceremony.