How to send variables to a method in a JavaScript modular pattern

I am trying to achieve something similar to the code snippet below. However, it seems to be invalid as it does not allow passing variables, specifically 'min' and 'max' in this case.

Is there a way to achieve this functionality? If so, how can it be done?

Thank you. J.

var utils = (function() {

    function randomRange(min, max) {
        return ((Math.random() * (max - min)) + min);
    };

    return {
        randomRange : randomRange(min, max);
    };

}());

utils.randomRangeRound(20,5);

Answer №1

If you are looking to make this function work:

utils.randomRangeRound(20,5);

you can achieve it like this:

var utils = {
    randomRangeRound: function(min, max) {
        return ((Math.random() * (max - min)) + min);
    }
};

Alternatively, if you have various methods on the utils object scattered across your code:

var utils = utils || {};

utils.randomRangeRound = function(min, max) {
    return ((Math.random() * (max - min)) + min);
}

Answer №2

On the flip side, your code is very close to being correct but the issue lies in the syntax:

var utilities = (function() {

    this.generateRandomNumber = function (minimum, maximum) {
        return ((Math.random() * (maximum - minimum)) + minimum);
    };

}());

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

Utilize React HOC (Higher Order Component) and Redux to retrieve data and pass it as props

In my quest to develop a Higher Order Component (HOC) that can execute methods to fetch data from the backend and display a loader mask during loading, I encountered a challenge. I aim to have the flexibility of passing different actions for various compon ...

Guide to Embedding StencilJS components in a Storybook React Application

I am currently in the process of integrating Stencil and Storybook within the same project. While following this setup guide and this one, I encountered a step that requires publishing the component library to NPM, which is not my desired approach. In my ...

Can the order of React lifecycle events be reliably predicted across different components?

Is there a clear documentation on the guarantees of React lifecycle order across separate components? For instance, if I have: <div>{ x ? <A /> : <B /> }</div> When x changes from true to false, one component will unmount and the ...

Using JavaScript promises to handle connection pooling and query execution

I am contemplating whether this approach is on the right track or if it requires further adjustments. Should I consider promisifying my custom MySQL getConnection method as well? request: function(queryRequest) { return new Promise(function(re ...

XMLHttpRequest Refusing to Send Data

This snippet of code is crucial for the custom extension: let url = "https://mywebsite.com/data.php"; function sendRequest() { var client = new XMLHttpRequest(); client.open("POST", url, true); client.setRequestHeader("Content-Type", "text/pla ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...

Manipulate JSON data in a Node.js loop

Currently, I am working on a monitoring system that will indicate on a website whether a server is up or down. I have experimented with various methods such as regex and replacement to modify the JSON file. My main objective is to dynamically change the "s ...

Tips for revealing a hidden div by clicking on another div?

I have a Google visualization chart inside a div tag. I would like to display this chart in a pop-up box when clicking on the chart's div. I am utilizing jQuery for this feature. ...

Tips for creating a clickable A href link in the menu bar that triggers an accordion to open in the body when clicked - html

Is there a way to open the first accordion when clicking on the "open 1st accordion" link, and do the same for the second link? The accordions themselves work perfectly fine, I just need a way to trigger them from outside their scope by clicking on links i ...

When attempting to bind various data to a single div using knockout js, the issue of duplicate records appearing arises

I am encountering an issue with a div that is set up to display 10 records at a time. When the user clicks on the next link, the next set of 10 records should be loaded from the server. However, after binding the newly added records, they are being shown m ...

display the text content of the chosen option on various div elements

I created a subscription form that includes a category dropdown select field. The selected option's text value needs to appear 4 times within the form. It's all part of a single form. <select name="catid" onchange="copy()" id="catid" class="i ...

The Angular 5 keyup event is being triggered twice

My app is incredibly simple, just a basic hello world. To enhance its appearance, I incorporated bootstrap for the design and ng-bootstrap for the components. Within one of my TS files, you will find the following code: showMeTheKey(event: KeyboardEvent) ...

Can someone recommend a different approach for handling a lengthy series of "if argA == argB do..." statements?

Note: due to the possibility of attack.condition having multiple values, a switch statement is not a viable solution! Currently I have an enum that will continue to expand: enum Condition { Null = 0x0001, SelfIsUnderground = ...

Developing a table with JavaScript by parsing JSON data

Starting off, I am relatively new to working with JavaScript. Recently, I attempted to generate a table using data from a JSON file. After researching and following some tutorials, I successfully displayed the table on a web browser. However, I noticed tha ...

The IsArray() function in IE8 encounters an issue where it expects an error object

I am interested to know why IE8 is having trouble with this line of code: if (isArray(obj)) When I check in the IE8 javascript console, I see the following: >>obj {...} >>typeof(obj) "object" >>Object.prototype.toString.call(obj) "[obj ...

I'm having trouble getting the data to parse correctly in ajax. Can anyone explain why it's not working?

I have implemented a system where an excel file is uploaded using AJAX, and information about the success or failure of the upload is sent from the upload page to the PHP page using json_encode. However, I am facing an issue with accessing this data indivi ...

The SMTP request for a one.com domain email is experiencing issues when sent from the render.com server

I have set up an Express JS server on render.com to handle SMTP calls to an email service hosted on one.com with a custom domain. Utilizing nodemailer to manage the SMTP call: app.post("/send-mail", validate(schema), (req, res) => { console. ...

Rendering Next.js app within HTML markup provided as a string

I am facing a challenge with integrating my Next.js app into an external HTML markup. The provided markup structure consists of the following files: header.txt <html> <head> <title>Some title</title> </head> < ...

Retrieving data from a React state in one component and utilizing it in a separate component

Thank you for taking the time to assist me with this challenge. I am currently working on a project that involves creating the state goodData in one component called AddProduct and accessing it in another component named ActionBox, both within the same j ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...