How to useMap in Javascript

In this approach, We are using a Map data structure where keys are enum values, and values are their string representations.

Syntax:

const enumMap = new Map([
[ENUM.VALUE1, 'String1'],
[ENUM.VALUE2, 'String2'],
// ... other enum mappings
]);
const stringValue = enumMap.get(enumValue);

Example: In this example, we have used the Map data structure to establish a direct mapping between enum values and their corresponding string representations.

Javascript




const OPERATION = {
    ADD: 'Addition',
    SUBTRACT: 'Subtraction',
};
 
const operationMap = new Map([
    [OPERATION.ADD, 'Addition'],
    [OPERATION.SUBTRACT, 'Subtraction'],
]);
 
const currentOperation = OPERATION.ADD;
const operationString = operationMap.get(currentOperation);
console.log(operationString);


Output

Addition


Convert a JavaScript Enum to a String

Enums in JavaScript are used to represent a fixed set of named values. In JavaScript, Enumerations or Enums are used to represent a fixed set of named values. However, Enums are not native to JavaScript, so they are usually implemented using objects or frozen arrays. In this article, we are going to explore various approaches to converting a JavaScript enum to a string representation.

These are the following ways to convert an enum to a string:

Table of Content

  • Using Object Key
  • Using a Switch Statement
  • Using Map

Similar Reads

Approach 1: Using Object Key

In this approach, we’ll use the fact that object keys are strings. Each enum value corresponds to a key in the object. We can use the enum value as a key to retrieve its corresponding string representation....

Approach 2: Using a Switch Statement

...

Approach 3: Using Map

In this approach, We switch on the enum value and return the corresponding string....