Best practices for utilizing an enum in JavaScript objects

In the past, I would create classes with a type property in traditional OOP languages such as Swift or Java:

struct ClassA {
    enum Type {
        case b, c, d
    }

    var type: Type
}

and then use it like this:

let a = ClassA(type: .b)

In ES6, a similar construction would be:

const Type = {  
    a: 0,
    b: 1,
    c: 2,
}

class ClassA {
    constructor(type) {
        this.type = type
    }
}

However, there are some issues from my perspective:

  • To build a ClassA object, the user must also import Type
  • Type doesn't feel like a natural part of ClassA

Is my code acceptable for JavaScript? Are these described problems typical in JavaScript? Is there a better approach to this issue?

The current problem I am trying to address is the following:

I have multiple types of user activities represented as objects. While they share many similarities like name, date, duration, etc., they need to be displayed differently based on their types.

My initial solution was to assign all essential fields with their respective types to each object.

Answer №1

Creating an object with enum-like behavior in JavaScript

There isn't a direct way to implement enums in JavaScript, so you'll have to find workarounds to mimic their functionality. However, relying too heavily on this approach may lead to unnecessary complexity and bloat in your codebase.

One option is to use constants within a class:

class ClassA {
    constructor(type) {
        this.type = type
    }
}

Object.defineProperties(ClassA, {
    TYPE_A: { enumerable: true, value: 0},
    TYPE_B: { enumerable: true, value: 1},
    TYPE_C: { enumerable: true, value: 2},
});

let instance = new ClassA( ClassA.TYPE_A );

Alternatively, you could consider using TypeScript, which provides enum support at compile-time.

If simulating enums doesn't seem ideal for your situation, are there better alternatives?

The scenario involves different types of user activities that share common attributes but need to be displayed based on their types.

One suggestion could be to structure the objects with essential fields corresponding to their types. However, without more specific details, it's challenging to provide a definitive solution.

Considering the nature of the data and its processing, using plain objects or JSON literals might suffice, possibly converting the type into a string for clarity.

Answer №2

Traditionally, the problem is typically resolved in the following manner:

class ClassA {
    constructor(category) {
        this.category = category;
    }
}
ClassA.CATEGORY_A = 0;
ClassA.CATEGORY_B = 1;
ClassA.CATEGORY_C = 2;

var example = new ClassA(ClassA.CATEGORY_B);

If desired, you have the option to use Object#defineProperty to establish fixed, read-only properties rather than typical ones.


In my opinion, the equivalent code written in ES3 syntax is more concise and direct.

function ClassA(category) {
    this.category = category;
}
ClassA.CATEGORY_A = 0;
ClassA.CATEGORY_B = 1;
ClassA.CATEGORY_C = 2;

var example = new ClassA(ClassA.CATEGORY_B);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of transforming a string into an angular binding?

I have a variable called message that contains the text "you are moving to {{output.number}}". I attempted to insert this into a div element using $("#message").html(message); However, it just displayed the entire string without replacing {{output.number ...

Controller method remains inaccessible despite multiple attempts with Javascript ajax Get call

I've tried numerous solutions for this issue, but I'm still unable to make it work. My goal is to invoke a controller method that accepts a parameter and returns a string based on that parameter. Despite using an ajax GET request, the outcome is ...

Press the div using JavaScript and jQuery

Is it possible in JavaScript to automatically click on a hidden div once it is displayed? For instance, imagine we have a div with the style "display:none;" like so: <div style="display:none;" id="button">Hello World</div> Once this div&apos ...

Sentry alert: Encountered a TypeError with the message "The function (0 , i.baggageHeaderToDynamicSamplingContext) does not

My website, which is built using Next.js and has Sentry attached to it, runs smoothly on localhost, dev, and staging environments. However, I am facing an issue when trying to run it on my main production server. The error message displayed is as follows: ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Allow images to be uploaded using the browser-policy package in Meteor

Can anyone help me figure out how to use Sir Trevor JS in Meteor for uploading images without encountering this error message? When attempting to load the image 'blob:http%3A//localhost%3A3000/a28ef7dc-ee51-4290-9941-6b8fc317e685', I am receivin ...

utilizing JSON data in a React application

I am working on a React project that involves a parent to grandchild hierarchy. In my code, I am passing values as JSON Objects. There are two input boxes where users can enter values and a button that stores and displays the values when clicked. Below is ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

Node.js is encountering an undefined parameter in the function definition

I've encountered an issue while working on an application utilizing MongoDB as the database and node.js. I have a function that is supposed to receive a parameter named orderedBy, but when I console.log it, it appears as undefined. Can someone help me ...

When using Material-UI's <Table/> component, an error is thrown stating that the element type is invalid

Struggling with material-ui Table is not familiar territory for me, especially since I have used it in numerous projects before. Currently, I am utilizing @material-ui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33505c41567 ...

Having trouble retrieving the $_SESSION variable accurately from AngularJS

I am working with angularjs and need to retrieve a php session variable. I have created a php file named session.php with the following content: $_SESSION['phone'] = '55551864'; return json_encode($_SESSION['phone']); In my ...

Tips for creating a state change function using TypeScript

Imagine the temperature remains constant for 20 minutes, but at the 21st minute, it changes. The state change is determined by a programmable state change function. How can I create a function to calculate the difference in state change? if(data.i ...

The issue of AngularJS failing to bind object properties to the template or HTML element

Just dipping my toes into angularJS, following Todd Motto's tutorials, and I'm having trouble displaying object properties on the page. function AddCurrentJobs($scope){ $scope.jobinfo = [{ title: 'Building Shed', description: ...

JavaScript mouse and touch movement events (mousemove, pointermove, touchmove) are not always accurate

I'm currently working on developing a JavaScript whiteboard and have implemented the following code: let lastTimestamp = 0; const fps = 1000/60; document.addEventListener("pointermove", moveMouse, false); function moveMouse (e) { e.preve ...

Modifying the default value script to function across various rows

Utilizing a script called jquery.defaultvalue.js, I have added default text to various input fields on a form: <script type='text/javascript'> jQuery(function($) { $("#name, #email, #organisation, #position").defaultvalue("Name", "Emai ...

Can you please explain the significance of file.max and file.FBX within the context of a model in three.js

I am currently working on developing a video game using three.js. Recently, I downloaded a model from the internet and upon checking the directory, I found the following files: city.obj city.mtl city.max city.FBX After some research, I learned that cit ...

I am seeing the object in req.body displayed in reverse order within my Node.js and Express backend application

I encountered an issue while developing a To-do list web application using the MERN stack with Redux. The problem arises when I try to send post data to the backend. In my form, the textfield area is named 'task' (e.g., ) and I input 'jonas& ...

When incorporating @babel/standalone, a JavaScript memory limit is exceeded

I am currently working on a React app that I developed using create-react-app. My main goal is to take user input as code and then evaluate it in order to render the output. Here's what I have attempted so far: import React, { Component } from &apos ...

How to use Vanilla JavaScript to toggle a click event on a list item (LI) that

I have a script that scans through a webpage and identifies a unique string, for example: multus –a –um. The page contains several <LI> elements with various text content, including instances of multus –a –um. I need a solution to locate an & ...

Is there a method to update the res object following a couchbase DB call without encountering the error "Error: Can't set headers after they are sent"?

let express = require('express'); let searchRoute = express.Router(); searchRoute.get('/', function(req, res, next) { console.log('1'); databaseCall(function(error, result) { if (error) { res.sta ...