Enums in Javascript: Tutorial & Examples

Updated: February 20, 2023 By: Khue Post a comment

This succinct, straight-to-the-point article is about enums in Javascript. You will learn what an enum is and how it can be used.

Overview

An enum, short for enumeration, is a data type that allows a developer to define a set of named constants. In other words, an enum is a collection of values that do not change, and each value has a corresponding name.

The example below demonstrates how to create an enum in Javascript:

const Colors = {
  RED: 'red',
  BLUE: 'blue',
  GREEN: 'green'
};

To use an enum, you can simply reference the values by their name, like so:

let myColor = Colors.RED;
console.log(myColor);

Output:

red

Using an enum can make the code more readable and easier to maintain. Instead of hard-coding values throughout the code, enums provide a centralized and easily modifiable way to define and use constants.

Now, it’s time to explore some real-world use cases and examples.

Examples

User Roles

In the example below, the UserRoles enum is used to define the different roles that a user can have, and the hasAdminAccess function uses the enum to determine whether a user has administrative access based on their role:

const UserRoles = {
  ADMIN: 'admin',
  MEMBER: 'member',
  GUEST: 'guest',
};

function hasAdminAccess(userRole) {
  return userRole === UserRoles.ADMIN;
}

const user1 = {
  name: 'Sling Academy',
  role: UserRoles.ADMIN,
};

if (hasAdminAccess(user1.role)) {
  console.log('User1 has admin access');
  // do some admin stuff
} else {
    console.log('User1 does NOT have permission to access this page');
}

const user2 = {
  name: 'Blazing Bull',
  role: UserRoles.GUEST,
};
if (hasAdminAccess(user2.role)) {
  console.log('User2 has admin access');
  // do some admin stuff
} else {
    console.log('User2 does NOT not have permission to access this page');
}

Output:

User1 has admin access
User2 does NOT not have permission to access this page

Weather Conditions

In a weather app, an enum could be used to define the different types of weather conditions, such as sunny, cloudy, or rainy.

The code:

const WeatherConditions = {
  SUNNY: 'sunny',
  CLOUDY: 'cloudy',
  RAINY: 'rainy'
};

function getWeatherIcon(condition) {
  switch (condition) {
    case WeatherConditions.SUNNY:
      return '☀️';
    case WeatherConditions.CLOUDY:
      return '☁️';
    case WeatherConditions.RAINY:
      return '🌧️';
    default:
      return '❓';
  }
}

console.log(getWeatherIcon(WeatherConditions.SUNNY));

Output:

☀️

Game Levels

In a game, an enum could be used to define the different levels of difficulty, such as easy, medium, or hard:

const DifficultyLevels = {
  EASY: 'easy',
  MEDIUM: 'medium',
  HARD: 'hard',
};

function startGame(level) {
  switch (level) {
    case DifficultyLevels.EASY:
      console.log('Start the game with easy difficulty');
      break;
    case DifficultyLevels.MEDIUM:
      console.log('Start the game with medium difficulty');
      break;
    case DifficultyLevels.HARD:
      console.log('Start the game with hard difficulty');
      break;
    default:
      throw new Error('Invalid difficulty level');
  }
}

startGame(DifficultyLevels.MEDIUM);

Output:

Start the game with medium difficulty

Product Categories

In an e-commerce application, an enum could be used to define the different product categories, such as electronics, clothing, or home goods:

const ProductCategories = {
  ELECTRONICS: 'electronics',
  CLOTHING: 'clothing',
  HOME_GOODS: 'home_goods',
};

function getProductList(category) {
  console.log(`Retrieving products in the ${category} category...`);
}

getProductList(ProductCategories.CLOTHING);

Output:

Retrieving products in the clothing category...

Types of Currencies

In a finance application, an enum could be used to define the different types of currencies, such as USD, EUR, or JPY:

const Currencies = {
  USD: 'USD',
  EUR: 'EUR',
  JPY: 'JPY'
};

function convertCurrency(amount, fromCurrency, toCurrency) {
  // your currency conversion logic here
  console.log(`Converting ${amount} ${fromCurrency} to ${toCurrency}...`);
}

convertCurrency(100, Currencies.USD, Currencies.EUR); 

Output:

Converting 100 USD to EUR..