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
})
Sign up to request clarification or add additional context in comments.

2 Comments

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?
make constants.js file in your project and put this into file like this export const WeekDays
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);

Comments

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 Comments

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 you'll have to export the "enum", then you can import it in other files. See CommonJS: flaviocopes.com/commonjs
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.