loop over enum in javascript

To loop over an enum in JavaScript, you can use the for...in loop. Here's an example:

index.tsx
// Define an enum
const Fruit = {
  APPLE: 'apple',
  BANANA: 'banana',
  ORANGE: 'orange'
};

// Loop over the enum values
for (let fruitKey in Fruit) {
  if (Fruit.hasOwnProperty(fruitKey)) {
    console.log(Fruit[fruitKey]);
  }
}
234 chars
14 lines

In the above example, we define an enum called Fruit and then use a for...in loop to loop over its values. We use the hasOwnProperty method to ensure that we only get the values that belong to the enum, and not any inherited properties. Finally, we log each value to the console.

related categories

gistlibby LogSnag