Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptEnums in JavaScript

Enums in JavaScript

Enums in JavaScript are used to represent a fixed set of named values. They allow developers to define a list of named constants, which can be used throughout the codebase to increase code readability, maintainability and prevent errors.

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.

To ensure the immutability of Enums in JavaScript, you can follow these guidelines:

Object.freeze() Method: One way to create an Enum-like object is by defining a plain JavaScript object with constant property values, and then using Object.freeze() to prevent any further modification. This will ensure that the object and its properties cannot be changed or mutated. You can use the Object.freeze() method to prevent any changes to the object. Once an object is frozen, you cannot add, modify or delete any of its properties. You can use this method to create an immutable object that represents your Enum.

Syntax:

Object.freeze()

Use Object.defineProperty() Method: You can use the Object.defineProperty() method to define properties that cannot be changed, added, or deleted. You can use this method to create a read-only property for each Enum value. You can use the Object.defineProperty() method to define properties that cannot be changed, added, or deleted. You can use this method to create a read-only property for each Enum value.

Use TypeScript: TypeScript is a superset of JavaScript that includes support for Enums. Using TypeScript, you can define Enums in a way that guarantees their immutability.

Example 1: In this example, we will see the use of Object.freeze() method.

Javascript




const DaysOfWeek = Object.freeze({
    SUNDAY: 0,
    MONDAY: 1,
    TUESDAY: 2,
    WEDNESDAY: 3,
    THURSDAY: 4,
    FRIDAY: 5,
    SATURDAY: 6
});
  
// Try to modify the enum
// This will not change the Sunday variable
DaysOfWeek.SUNDAY = 7; 
console.log(DaysOfWeek.SUNDAY);


Output:

0

In this example, we create an Enum object called DaysOfWeek using Object.freeze(). The Object.freeze() method makes the object immutable, so we cannot add, modify or delete properties from the object.

ES6 Symbol: Another approach to creating an Enum in JavaScript is to use ES6 Symbols. Symbols are unique identifiers that cannot be duplicated and can be used to define constant values that are guaranteed to be unique and unchanging.

Example: Here’s an example of how to define an enum using ES6 Symbols

Javascript




const myEnum = Object.freeze({
    FOO: Symbol('foo'),
    BAR: Symbol('bar'),
    BAZ: Symbol('baz')
});
  
console.log(myEnum.FOO); // Symbol(foo)
  
// Attempting to modify the enum
// values will have no effect
myEnum.FOO = Symbol('newFoo');
console.log(myEnum.FOO); // Symbol(foo)
  
// Adding a new property to the enum
// object will also have no effect
myEnum.QUX = Symbol('qux');
console.log(myEnum.QUX); // undefined


Output:

Symbol(foo)
Symbol(foo)
undefined

In this example, we’re defining an enum called myEnum using Object.freeze() to prevent any modifications to the object. We’re using Symbol() to create unique symbols for each enum value.

Using a Closure: You can also use a closure to create an Enum. A closure is a function that has access to variables in its outer function scope. By creating an inner function that returns a value, we can make the variable in the outer function scope read-only.

Example: In this example, we will use closure.

Javascript




const DaysOfWeek = (function () {
    const days = {
        SUNDAY: 0,
        MONDAY: 1,
        TUESDAY: 2,
        WEDNESDAY: 3,
        THURSDAY: 4,
        FRIDAY: 5,
        SATURDAY: 6
    };
    return {
        get: function (name) {
            return days[name];
        }
    };
})();
  
// Try to modify the enum
// This will not have any effect
DaysOfWeek.SUNDAY = 7; 
console.log(DaysOfWeek.get('SUNDAY')); // Output: 0


Output:

0

In this example, we use a closure to create an object called DaysOfWeek. The days object is defined in the outer function scope and is not accessible from outside the function. The inner function get returns the value of the property with the given name from the days object. Since the days object is not directly accessible, it cannot be modified from outside the closure.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments