Defining Ecmascript function parameters with enumerated values

Is it feasible to have an enum value for a parameter in Ecmascript function?

For instance, consider this scenario:

export const testFunc = (param1) => {

};

Suppose we want the param variable to only accept values of "val1","val2","val3"

export const testFunc = (param = {"val1","val2","val3"}) =>{

};

Answer №1

JavaScript doesn't have a built-in enum type, but you can simulate it by checking if the parameter is one of the predefined values:

const checkEnum = (param) =>{
  if (!["val1","val2","val3"].includes(param)) {
    throw new Error('Invalid param passed');
  }
  // continue with the function
};

Answer №2

According to Snow on this thread, JavaScript lacks enums. However, TypeScript does support enums (more information here), so if you require enums (along with other features), TypeScript could be a viable option as it compiles to JavaScript.

If TypeScript isn't the path you want to take, an alternative approach is to create an enum-like object:

const TheEnum = {
    val1: 0,
    val2: 1,
    val3: 2,
    0: "val1",
    1: "val2",
    2: "val3",
    valid(value) {
        return typeof param === "number" && !!TheEnum[param];
    }
};

...and then verify the received value:

export const testFunc = (param) => {
    if (!TheEnum.valid(param)) {
        throw new Error("'param' must be a TheEnum value");
    }
    // ...
};

It's worth noting that this example "enum" provides mappings for both symbolic names (val1, etc.) and their corresponding values, similar to how it's done in TypeScript. This can be useful when you need to display the name "val1" instead of its associated value 0 in messages or other contexts.

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

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

Javascript /// <field type=?> used to define properties for individually customized objects

Exploring the XML javascript comment syntax in Visual Studio and encountering some confusion. Specifically, I have a query regarding custom types. For example, consider a custom type like... namespace.types.User = function(_id, _name) { /// <field ...

The looping function in Vue.js data is not functioning properly

Currently, I am developing a shopping cart system using Laravel session and Vue.js. Below is a snippet of my Vue.js code where I loop through the products and add them to the cart/session on click. <div v-for="product in products"> <div cla ...

Javascript's simplistic addition function is not functioning properly

Learning JavaScript has been a bit challenging for me, especially when it comes to simple concepts. I'm trying to write code that sums two numbers together, but for some reason, it's not working. function sum() { var number1 = documen ...

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

React Axios.post request fails with 422 error code due to data validation errors

I am facing an issue while trying to send an item object to the array using the post method. The error message I receive is: POST https://applic.com/api/v1/todos?expand=createdBy 422 (Data Validation Failed.) Here is my item object: creat: Sat Jun 01 201 ...

Setting a default value in a dynamic dropdown using AngularJS

I could really use some assistance with my issue as I am fairly new to working with AngularJS. My dilemma is related to setting the default value in a select option when there is only one item available due to it being a dynamic select option. Though there ...

Utilizing setInterval for automatic page refreshing

I've been working on a setInterval function to continuously check for new comments, select them, and post them. While it's somewhat functional at the moment, it's not behaving exactly as I intended. Currently, what happens is that every thre ...

A WordPress website featuring the impressive capabilities of the Three.js JavaScript 3D library

I attempted to integrate the Three.js JavaScript 3D library into my WordPress website by including three.min.js in various parts: Within the body of a post <script src="/three.min.js"></script> In the footer <script type='text/ ...

Node.js: Issues with using async await inside a map function

Currently, I am in the process of developing a clone of Tinder. My focus right now is on working on the match/post request within my backend code. This request involves calling a separate function named match, which is triggered after the current user ha ...

Sending JSON data stored in a JavaScript variable through a jQuery POST request

I am currently attempting to retrieve data from a remote location using a JQuery post method. It works perfectly fine when I directly input the data to be posted, but for some reason, it fails when I store the JSON in a JavaScript variable and pass it in. ...

Is it necessary for me to use a .jsx extension when saving my React component files?

After working with React for a few months, I recently noticed that some of my files have the .js extension while others have the .jsx extension. Surprisingly, when I write JSX code in the .js files, everything still functions correctly. Is there any signif ...

Creating HTML dynamically upon page load with the use of JavaScript

I have a project where I need to create a small block of JavaScript that can be embedded in various websites' home pages. This script will automatically call a URL when visitors hit the home page, collecting specific statistics and returning a small i ...

Creating a new dynamic page can be achieved by clicking on a dynamically generated link. Would you like to learn how to do that?

Recently, I developed a custom API using Node.js to retrieve information about blogs from Medium.com. The API currently provides: The author/main picture of the article Title A link to the article on medium.com (redundant) The entire article text in the ...

Glitch in the system: Customizing buttons with Google Maps API v3

With my custom buttons on Google Maps, I am able to create markers with different icons for each button. However, when I click on one button to create a marker and then click on another button to create another marker, the two buttons end up overlapping ea ...

The JQuery Full Calendar embedded within a div tag will only become visible once the calendar click event is activated

Upon entering my page, various sections (images, calendar, info, etc) are displayed within div tags. These div tags are hidden or shown based on which navigation link is clicked on the left side of the page. However, I am facing an issue where the calendar ...

Can the chrome console be used to showcase the contents of objects?

When I have a line of code, and I try to output it to the console, I only see [object Object] instead of the actual object types. console.log(`%c ${args[args.length-1]} ${performance['now'](true, args[args.length-1])} [(${args.slice(0, args.leng ...

What are the possible reasons for my load function failing intermittently?

I have encountered an issue with my app where sometimes the content is not loaded into a dialog. Most of the time it works perfectly, but occasionally it fails to display the content. Here is the code snippet that I am using: $('#popup_background&apo ...

Switch background and disable hover effect with a click

I'm facing some issues with JavaScript and I can't seem to solve the problem on my own. What I want is, when I click on #footerblock, for the background of #footerblock to change, and then for the footer to lose its "hover effect". <script> ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...