3

Is it possible to create enum values in JavaScript and assign them to integer values, similar to other languages. For example in C#, I declare an enum in the following way:

enum WeekDays { Monday = 0, Tuesday =1, Wednesday = 2, Thursday = 3, Friday = 4, Saturday =5, Sunday = 6 } 

    4 Answers 4

    7

    You can use object as an enum after freezing it like example below:

    const WeekDays = Object.freeze({ Monday: 0, Tuesday: 1, Wednesday: 2, Thursday: 3, Friday: 4, Saturday: 5, Sunday: 6 }) 
    2
    • thanks, sorry i'm new to javascript, why do we use object.freeze and how can i put this in a file and use it in different parts of my application.when reading integer values from database, how can i convert it back to enum values?
      – arve
      CommentedMay 17, 2020 at 22:38
    • make constants.js file in your project and put this into file like this export const WeekDays
      – fazlu
      CommentedMay 17, 2020 at 22:46
    4

    You can create a simple object and export it via module.exports:

    // days.js module.exports = { Monday: 0, Tuesday: 1, Wednesday: 2, Thursday: 3, Friday: 4, Saturday: 5, Sunday: 6 } // file-where-you-want-to-use.js const DAYS = require('./days.js'); console.log(DAYS.Monday); 
      1

      You can use a plain old object:

      const WeekDays = { Monday: 0, Tuesday: 1, Wednesday: 2, Thursday: 3, Friday: 4, Saturday: 5, Sunday: 6 } const day1 = WeekDays.Monday; const day2 = WeekDays.Tuesday; console.log(day1, day2, day1 === day2); console.log(day1 === WeekDays.Monday, day2 === WeekDays.Tuesday);

      2
      • thanks, I want to have this enum available through all my application. so if I put this in its own file, enum.js, how can use the weekdays in other files?
        – arve
        CommentedMay 17, 2020 at 22:34
      • @arve you'll have to export the "enum", then you can import it in other files. See CommonJS: flaviocopes.com/commonjs
        – Olian04
        CommentedMay 17, 2020 at 23:52
      0

      To add some sort of variables that you'd like to use:

      // days.js module.exports = { Monday: 0, Tuesday: 1, Wednesday: 2, Thursday: 3, Friday: 4, Saturday: 5, Sunday: 6 } // file-where-you-want-to-use.js const DAYS = require('./days.js'); const firstDayOfWeek = 'Monday'; console.log((DAYS)[firstDayOfWeek]); // 0 

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.