How to usea Switch Statement in Javascript

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

Syntax:

function enumToString(enumValue) {
switch (enumValue) {
case ENUM.VALUE1:
return 'String1';
case ENUM.VALUE2:
return 'String2';
// ... other cases
default:
return 'DefaultString';
}
}

Example: In this example, the switch statement is used to convert a given enum value to its associated string.

Javascript




const ENUM = {
    VALUE1: 'A',
    VALUE2: 'B',
};
 
function enumToString(enumValue) {
    switch (enumValue) {
        case ENUM.VALUE1:
            return 'String1';
        case ENUM.VALUE2:
            return 'String2';
        default:
            return 'DefaultString';
    }
}
 
const currentEnumValue = ENUM.VALUE1;
const stringValue = enumToString(currentEnumValue);
console.log(stringValue);


Output

String1

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....