Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Convert a Number to a String in JavaScript
Next article icon

Convert a JavaScript Enum to a String

Last Updated : 30 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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.

Syntax:

const enumObject = {
VALUE1: 'String1',
VALUE2: 'String2',
// ... other enum values
};
const stringValue = enumObject[enumValue];

Example: In this example, we are using the object keys, to convert a specific enum value to its corresponding string representation

JavaScript
const status = {     SUCCESS: 'Operation Successful',     ERROR: 'Operation Failed',     PENDING: 'Operation Pending', };  const currentStatus = 'ERROR'; const statusString = status[currentStatus]; console.log(statusString);  

Output
Operation Failed 

Approach 2: Using a Switch Statement

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 

Approach 3: Using Map

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 

Next Article
Convert a Number to a String in JavaScript

A

amanv09
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • Convert Array to String in JavaScript
    In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen
    8 min read
  • JavaScript - Convert String to Array
    Strings in JavaScript are immutable (cannot be changed directly). However, arrays are mutable, allowing you to perform operations such as adding, removing, or modifying elements. Converting a string to an array makes it easier to: Access individual characters or substrings.Perform array operations s
    5 min read
  • Convert a Number to a String in JavaScript
    These are the following ways to Convert a number to a string in JavaScript: 1. Using toString() Method (Efficient and Simple Method)This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type. [GFGTABS] JavaScript let a = 20;
    1 min read
  • JavaScript - Convert a String to Boolean in JS
    Here are different ways to convert string to boolean in JavaScript. 1. Using JavaScript == OperatorThe == operator compares the equality of two operands. If equal then the condition is true otherwise false. Syntax console.log(YOUR_STRING == 'true');[GFGTABS] JavaScript let str1 = "false";
    3 min read
  • Convert a String to Number in JavaScript
    To convert a string to number in JavaScript, various methods such as the Number() function, parseInt(), or parseFloat() can be used. These functions allow to convert string representations of numbers into actual numerical values, enabling arithmetic operations and comparisons. Below are the approach
    4 min read
  • JavaScript - Convert Byte Array to String
    Here are the various methods to convert Byte Array to string in JavaScript. 1. Using WebAPI TextDecoder.decode() MethodThe TextDecoder API is a modern and efficient way to convert a byte array (Uint8Array) to a string. It’s supported in both browsers and Node.js. [GFGTABS] JavaScript const byteA = n
    2 min read
  • Convert an Array to JSON in JavaScript
    Given a JavaScript Array and the task is to convert an array to JSON Object. Below are the approaches to convert an array to JSON using JsvaScript: Table of Content JSON.stringify() methodObject.assign() methodJSON.stringify() methodThe use of JSON is to exchange data to/from a web server. While sen
    2 min read
  • How to Convert String to Camel Case in JavaScript?
    We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
    4 min read
  • JavaScript | Encode/Decode a string to Base64
    To encode or decode strings in JavaScript, we can use the built-in functions provided by the language. These functions help in encoding special characters in a URL or decoding encoded strings back to their original form. 1. btoa() MethodThis method encodes a string in base-64 and uses the "A-Z", "a-
    6 min read
  • Convert base64 String to ArrayBuffer In JavaScript
    A Base64 string represents binary data in an ASCII string format by translating it into a radix-64 representation. Often used to encode binary data in text-based formats like JSON or HTML, it needs to be converted back into its original binary format for further processing. An ArrayBuffer in JavaScr
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences