What is the best way to save multiple instances of a JavaScript function with varying parameters in an array and execute them

I'm looking for a way to efficiently reuse a function multiple times with different ids depending on various conditions, such as select values. Instead of creating a new function for each id, I want a more dynamic approach to handle the potential multitude of ids in the future.

var getValue = function(id){

    var Element = document.getElementById(id);

    if(Element){
        if(Element.value){
            return " " + Element.value;
        }
        return "";
    }
    return "";
}

I have an array that contains several other functions:

FunctionList = [ SomeFunction, SomeFunction2 ];

Depending on certain criteria, I need to incorporate the getValue function into this array with varying parameters.

FunctionList.push(getValue(SomeId1));
FunctionList.push(getValue(SomeId2));
FunctionList.push(getValue(SomeOtherId));

In the end, I must concatenate the outputs of these functions (which are strings) into another string.

var updateCode = function(){
    var code = CodeHeader;
    for (var i=0; i<FunctionList.length; i++){
        code += FunctionList[i]();
    } 
    return code;
}

However, I am encountering challenges using it in this manner, as some elements within the array are not function names anymore. While I prefer solutions in pure JavaScript, I'm open to using jQuery or alternative frameworks if necessary.

Answer №1

If you want to create a custom function on the spot, you can utilize bind:

FunctionList.push(getValue.bind(null, SomeId1));

The first parameter (null here) serves as the context (this) during function execution.

This approach differs from your initial method:

FunctionList.push(getValue(SomeId1));

... because in the latter case, you are not pushing a function but the outcome of executing a function. On the other hand, bind creates a new function based on the provided one without immediately executing it.

Another Option

In the scenario where you consistently call the same function with varying arguments, you could opt for an array solely containing those arguments:

argumentList.push(SomeId1); // Not the function itself, just the argument
// ...and so forth

Subsequently, the revised version of updateCode would be:

var updateCode = function(){
    var code = CodeHeader;
    for (var i=0; i<argumentList.length; i++){
        code += getValue(argumentList[i]);
    } 
    return code;
}

... or using map for conciseness:

var updateCode = () => CodeHeader + argumentList.map(getValue).join("");

In the above one-liner, if your getValue function prepends the returned value with a space, you can skip that step and simply apply .join(" "). However, note that this adjustment may not handle empty return values in the same manner.

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 are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

Creating a Javascript function to turn lights off using CSS manipulation, similar to the feature found

Is there a way to use JavaScript to obscure all elements on a page except for one specific HTML element? This web application is optimized for Chrome, so CSS3 can also be utilized. ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

Obtaining HTML elements from JSON using jQuery (i.e., the opposite of serializing with Ajax)

I am looking to extract values from a set of controls (INPUT, SELECT, TEXTAREA) within a DIV and send them as JSON via Ajax to a server. Utilizing jQuery's serializeArray makes this process easy. After sending the JSON data, I expect the server to re ...

Tips for preserving textarea content upon clicking outside the area with the help of ajax

I am new to using the Froala editor and I am currently working on a feature where I need to save text in the textarea of the editor when the user clicks outside of it using Ajax. The ID of the content editor is #id_content. Here is a snippet of my form in ...

Using jQuery to track the status of checkboxes

Changing the checkbox status using the code: $(this).attr("checked", 'checked'); However, when trying to check the checkbox status afterwards, I received the following results: $(this).attr('checked'): "checked" $(this).is(':chec ...

How can UI tests be run in headless mode in Selenium 4 and above?

Selenium recently announced the release of Selenium 4, and they have also mentioned that there will be no support for PhantomJS from Selenium 4 onwards. Does this mean that Selenium no longer supports headless automation, or is there a different method t ...

Identify if a String Starts with Specific Characters

I am currently working on a JavaScript project where I need to detect if a string starts with specific letters using regex. If the condition is met, I want to perform certain actions. Specifically, I am searching for the value "window_" at the beginning of ...

Dealing with invalid JSON in Express: Best Practices

I am looking to handle cases of invalid JSON in my application. For example, if I receive "usern": "James" instead of "username": "James", I want to return a 400 status code. exports.create_user = async (req, res) =& ...

Encountered an error "Not Found" when attempting to establish an AJAX connection between Javascript and Rails

I'm having an issue with a simple Rails controller method. When I call it from JavaScript as an AJAX method, I get the error message "Not Found" in the JavaScript error log, even though the method works fine when accessed directly in the browser. What ...

Compatibility problem arising from the versions of ember-precompile, ember.js, and handlebars.js

Having trouble reading the precompiled templates in my HTML due to compatibility issues between ember-precompile, ember.js, and handlebars.js. My code looks like this: Includes the following files. <script src="../js/libs/jquery-1.10.2.js"></sc ...

Leverage the power of Fluentlenium to effortlessly upload a file using dropzone.js

Currently, I am trying to create a test for file uploading using Fluentlenium and DropZone.js (). Dropzone.js operates within a modal where users can drag and drop files or upload them traditionally. However, the test crashes as soon as the upload button ...

Step-by-step guide on utilizing $.each() for generating an interactive tooltip within datepicker Jquery

My Jquery datepicker displays a tooltip with the name of each holiday during a hover effect. I encountered a bug where the tooltip does not work when using $.each() instead of a for loop to display the tooltip. Here is the code snippet: $(".datepicker ...

Ways to call a DIV element in a PHP file from a different PHP file

I am facing an issue with referring to a specific <div> element from one .php page to another. The current code is redirecting me to the home page of the first page, instead of displaying the desired content. Can anyone provide guidance on how to ach ...

Having trouble extracting a JSON object from a POST request in Express v4 with the help of body-parser?

Currently, I am delving into the world of server-side code and learning about Node.js and Express. However, I am facing some challenges when it comes to receiving and parsing a JSON object sent from a POST request. Despite checking various resources (linke ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Enhancing the functionality of XMLHttpRequest.open()

How can I intercept and modify the arguments of the XMLHttpRequest.open() method? I attempted using the proxy method, but it was unsuccessful. I removed the override when XMLHttpRequest() was called: (function() { var intercepted = window.XMLHttpReque ...

Creating a collection of arrays that are named based on the properties of an object

After calling an ajax service, I received a collection of objects where Object (A) properties are Group, order, salary. For example, the objects could be [Employee, 1, 1500],[Management, 2, 2000], [Employee, 3, salary]. My task is to create an array for e ...

When using the each() function, the array shows a length of zero and does not

Although I am well-versed in PHP, my understanding of JQuery is lacking and I'm experiencing some difficulty with arrays. Despite researching numerous forum posts on the topic, I still can't seem to get it right. I believe I have an array struct ...