Enum value in javascript

JavaScript Enums

Although enum is a reserved word in JavaScript, JavaScript has no support for traditional enums. However, it is fairly easy to define enums using objects in JavaScript. For example, TypeScript has support for enums:

At runtime, TypeScript compiles the above code into the below enum-like object:

const Direction = < Up: 'Up', Down: 'Down', Left: 'Left', Right: 'Right' >;

This object has most of the features that you would expect from an enum:

  1. Get all allowed enum values: Object.keys(Direction) returns an array [‘Up’, ‘Down’, ‘Left’, ‘Right’]
  2. Check if a value equals an enum value: val === Direction.Up
  3. Check if a value is in the enum: Direction.hasOwnProperty(‘Up’)

However, there are a couple of limitations:

  1. You can modify the enum after instantiation. For example, Direction.sideways = ‘sideways’ .
  2. If val === undefined , then val === Direction.notAnEnumValue and val === Direction.Downe . So typos in enum properties can cause issues.
  3. No guarantee that property values don’t conflict. Direction.Down = ‘Up’ is valid.

You can make JavaScript objects immutable using Object.freeze() . Using Object.freeze() and a function, you can work around limitations (1) and (3).

function createEnum(values) < const enumObject = <>; for (const val of values) < enumObject[val] = val; >return Object.freeze(enumObject); > // createEnum(['Up', 'Down', 'Left', 'Right']);

Class-Based Approach

Dr. Axel Rauschmayer presents a much more sophisticated approach in this blog post using JavaScript classes. His approach would look more like this:

class Direction < static Up = new Direction('Up'); static Down = new Direction('Down'); static Left = new Direction('Left'); static Right = new Direction('Right'); constructor(name) < this.name = name; > toString() < return `Color.$this.name>`; > >

Here’s how you can work with the Direction class:

  1. Get all allowed enum values: Object.keys(Direction) returns an array [‘Up’, ‘Down’, ‘Left’, ‘Right’]
  2. Check if a value equals an enum value: val === Direction.Up.name
  3. Check if a value is in the enum: Direction.Up instanceof Direction

This approach is interesting, and there’s even a enumify npm package that implements this basic approach along with additional syntactic sugar. This approach also has the neat benefit that Direction.Downe.name throws an error, which means you don’t accidentally check undefined === undefined if you typo an enum property.

However, we generally recommend using Object.freeze() on a POJO to represent an enum. Enumify does offer advatanges and some neat syntactic sugar, but we think a POJO gets you most of the advantages with much less overhead.

More Fundamentals Tutorials

Источник

Using Enums (Enumerations) In Javascript

This post will explain how to implement and use enumerations (or enum types) in Javascript.

banner image

Enums are types that contain a limited number of fixed values, as opposed to types like Number or String which can have a wide range of values.

This is useful for many situations: For example, when describing seasons in temperate climates, you’ll want to limit the options to certain possible values: Summer , Winter , Spring and Autumn .

Let’s look at different ways of implementing this type of data:

Defining Enums as Object Keys#

For a basic implementation of enums, we can define an object to encapsulate the enum type, and assign a key for each enum value.

For example, we can represent seasons as on object with each season as the key, and a representative string as the value:

const Seasons =   Summer: "summer",  Autumn: "autumn",  Winter: "winter",  Spring: "spring" > 

We can also do this by using numbers as values:

const Seasons =   Summer: 0,  Autumn: 1,  Winter: 2,  Spring: 3 > 

It’s easy to make mistakes in your code. A developer can make the mistake of using integers outside the range of the ones defined, or make a spelling mistake when using strings.

const Seasons =   Summer: "summer",  Autumn: "autumn",  Winter: "winter",  Spring: "spring" > const mySeason = "summr"  // this would be false because of the spelling mistake in `mySeason`  console.log(mySeason === Seasons.Summer) 

Definitions from unrelated enums can overlap and cause conflicts:

 const Seasons =   Summer: 0,  Autumn: 1,  Winter: 2,  Spring: 3  >   const Fruits =   Apple: 1,  Orange: 1  >   // Ideally, this should never be true!  console.log(Seasons.Summer === Fruits.Apple) 

Enums with Symbols#

Symbols let us define values that are guaranteed not to collide with one another.

const Summer1 = Symbol("summer") const Summer2 = Symbol("summer")  // Even though they have the same apparent value // Summer1 and Summer2 don't equate  console.log(Summer1 === Summer2) // false  console.log(Summer1) 

We can define our enums using Symbols to ensure that they are not duplicated:

const Seasons =   Summer: Symbol("summer"),  Autumn: Symbol("autumn"),  Winter: Symbol("winter"),  Spring: Symbol("spring") >  let season = Seasons.Spring  switch (season)   case Seasons.Summer:  console.log('the season is summer')  break;  case Seasons.Winter:  console.log('the season is winter')  break;  case Seasons.Spring:  console.log('the season is spring')  break;  case Seasons.Autumn:  console.log('the season is autumn')  break;  default:  console.log('season not defined') > 

Using Symbols ensures that the only way we can assign an enum value is by using the values that we defined initially.

Please note that Symbols cannot be serialized into JSON, so if you plan on converting an object containing this enum into a JSON string, you should consider the previous method of using object keys instead

Making Enum Objects Immutable#

In the previous examples, it’s possible to change the value of an enum by modifying the enum object. For example, we can change the Seasons object like so:

const Seasons =   Summer: Symbol("summer"),  Autumn: Symbol("autumn"),  Winter: Symbol("winter"),  Spring: Symbol("spring") >  Seasons.Winter = "winter" // this will overwrite the `Symbol` with a string 

For larger codebases, these kind of errors may be introduced unintentionally. We can use Object.freeze to prevent these kind of changes:

const Seasons = Object.freeze(  Summer: Symbol("summer"),  Autumn: Symbol("autumn"),  Winter: Symbol("winter"),  Spring: Symbol("spring") >)  Seasons.Winter = "winter" // this won't change the `Seasons` object because its been frozen 

Enums with Classes#

To make our code more semantically correct, we can create a class to hold groups of enums.

For example, our seasons should have a way for us to identify that they all belong to a similar classification.

Let’s see how we can use classes and objects to create distinct enum groups:

// Season enums can be grouped as static members of a class  class Season   // Create new instances of the same class as static attributes  static Summer = new Season("summer")  static Autumn = new Season("autumn")  static Winter = new Season("winter")  static Spring = new Season("spring")   constructor(name)   this.name = name  > >  // Now we can access enums using namespaced assignments // this makes it semantically clear that "Summer" is a "Season"  let season = Season.Summer  // We can verify whether a particular variable is a Season enum  console.log(season instanceof Season) // true  console.log(Symbol('something') instanceof Season) //false  // We can explicitly check the type based on each enums class  console.log(season.constructor.name) // 'Season' 

Listing All Possible Enum Values#

If we used the class-based approach above, we can loop through the keys of the Season class to obtain all the enum values under the same group:

Object.keys(Season).forEach(season => console.log("season:", season)) // season: Summer // season: Autumn // season: Winter // season: Spring 

We can do the same with the object-based approach as well:

const Seasons = Object.freeze(  Summer: Symbol("summer"),  Autumn: Symbol("autumn"),  Winter: Symbol("winter"),  Spring: Symbol("spring") >)  Object.keys(Seasons).forEach(season => console.log("season:", season)) // season: Summer // season: Autumn // season: Winter // season: Spring 

When to Use Enums in Javascript?#

In general, enums are helpful if there are a definite number of fixed values for any one variable.

For example, the crypto standard library for Node.js has a list of supported algorithms, that can be considered an enum group.

Using enums in Javascript correctly will lead to better code that is more stable, easier to read and less error prone.

Источник

Enum in JS

Javascript Course - Mastering the Fundamentals

Enum is a data type in programming languages that defines a set of constant values. It is a distinct value type (i.e.) all values in an enum are unique. Using an enum makes the code readable and maintainable. Some examples of enum are all weekdays from Monday to Sunday, T-shirt sizes like S , M , L , XL , etc.

The pseudocode of an enum variable can look like below:

Does JavaScript Support Enum ?

Even though enum data type is widely used in many programming languages like C++ , Java , etc., Javascript doesn’t have a built-in enum data type. Enum’s functionalities can be implemented in Javascript using classes and objects.

Ways to Implement Enum in Javascript

Enum Using Objects

Enums can be implemented in Javascript using objects. The object can have key-value pairs where the key can be treated as the enum value, and the matter can be anything.

Let’s use a Javascript object to implement an enum for the directions such as north, east, west, and south.

One problem with the above implementation is that the values in the Direction object are mutable. Since enums are immutable, we can achieve immutability by freezing the object using the Object.freeze() method.

The Object.freeze() method freezes an object meaning new properties cannot be added, existing properties, and the object’s prototype cannot be re-assigned.

The values can be accessed line below :

Enum Using Symbols

One problem we see with the above approach is collision (i.e.) the value of one object may collide with the value of the other object. Let’s understand it with the enums Direction and Pole.

The output of the above code will be :

Even though the North direction and North pole are different enum instances, they are treated equally. Symbol can be used to overcome this issue.

Symbol is a built-in object whose constructor returns a value guaranteed to be unique. Let’s use symbols to implement the Direction and Pole enum.

The output of the above code is :

The above code returns false because the values of the Direction instance and Pole instance are different, as Symbol returns unique values.

Enum Using Classes

Enums can be implemented using Javascript classes, where each value will be the static instance of the class itself but with different values.

Let’s understand it with an example :

Let’s implement the Direction enum using Javascript classes.

The enum value can be accessed like below :

When to Use Enums in Javascript ?

Enums can be used in Javascript when it provides the below advantages :

  • Improves the readability and maintainability of the code.
  • Reduces errors caused by mistyping.
  • Useful when there is a fixed number of values like days of the week, months of the year, etc.

Learn About Important Concepts in JavaScript

Please visit Scaler Topics’ Javascript hub to learn more about Javascript

Conclusion

  • Enum is a data type in programming languages that defines a set of constant values.
  • All values in an enum should be unique.
  • Although the enum data type is widely used in many programming languages, Javascript doesn’t have the enum data type.
  • Enum can be implemented using objects, classes, and symbols in Javascript.
  • Symbol is a built-in object whose constructor returns a value that is guaranteed to be unique
  • Symbol avoids collision between two enums with the same values.

Источник

Читайте также:  Example Domain
Оцените статью