What is the correct way to add parameters to a function expression in JavaScript?

function executeFunction(func) {
  func();
}

var mathOperations = function(x, y) {
  var multiply = x * y;
  var add = x + y;
  var subtract = x - y;
  console.log("Addition: " + add);
  console.log("Subtraction: " + subtract);
  console.log("Multiplication: " + multiply);
}

executeFunction(mathOperations.bind(null, 9, 3));

What is the correct way to pass parameters into a function expression? Why does the line

executeFunction(mathOperations.bind(null, 9, 3));
not work?

Answer №1

executeFunction(()=>compute(12,4));

or compatible with es-5

executeFunction(function(){
  return compute(12,4)
});

Answer №2

The reason it is not functioning properly is because you are invoking the function.

Here are a couple of alternatives:

invokeFunction(mathOperation.bind(null, 9, 3));

or

invokeFunction(function () { return mathOperation(9, 3); });

Answer №3

The function calculation(9,3) was just run, and the result it produced - which happens to be undefined - is then passed on to callFunction.

Give this a shot:

function callFunction(fun, x, y) {
  fun(x, y);
}

var calculation = function(x, y){
  var product = x * y;
  var sum = x + y;
  var difference = x - y;
  console.log("Sum: " + sum);
  console.log("Difference: " + difference);
  console.log("Product: " + product);
}

callFunction(calculation, 9, 3);

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

Leveraging the Power of jsPDF in Your Google Apps Scripts

Is it feasible to integrate jsPDF into a Google Apps Script project? I am attempting to create documents using templated HTML, but certain CSS styles like background-color do not translate to PDF when using the getAs() function. Given the limitations of ...

Editing the app.js file can cause it to malfunction and stop working

As I work on designing a webpage for a construction company using a template, I face an issue with the js file named app.js. Whenever I make edits to the script, the entire HTML page loses its responsiveness as if the js file was never included in the firs ...

Ajax is transmitting the data, however, PHP is unable to receive it

I am utilizing the power of ajax to transmit data to a php function. My ultimate goal is to exhibit rows of data based on the variable $tweetdate. Below is the snippet of my ajax script: jQuery('#bootstrapModalFullCalendar').fullCalendar({ d ...

What is the speed difference between calling functions from require's cache in Node.js and functions in the global scope?

Let's imagine a scenario where we have two files: external.js and main.js. // external.js //create a print function that is accessible globally module.exports.print = function(text) { console.log(text) } Now let's take a look at main.js: ...

Leverage variables in the path of your Express.js route

Currently in the process of developing a web application using the MEAN stack and I have a specific scenario in mind: Users should be able to sign up, but then they must also register at least one company. Upon registering a company, the base URL struct ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

The contents of a JSON Object will not be logged by Node, no matter the approach

I am currently encoding data for a Node.js WebSocket server in JSON format. When attempting to display the contents of the JSON object on the server side, I am encountering the issue where Node simply logs object Object I have experimented with the follow ...

Searching for values within an array of objects by iterating through nested arrays to apply a filter

Having trouble returning the testcaseid from an array to this.filteredArray Able to fetch header value and all values of the array when the search word is empty. Seeking assistance with iterating through the testcaseid and header on the search input fiel ...

Tips for preserving login status even after the browser is shut down with the help of JavaScript

I need help with maintaining a user session in my chat application even when the browser is closed. After users log in for the first time, I want their credentials to be remembered by the browser (I'm currently using local storage). How can I ensure ...

Error occurred: Undefined module imported

CounterDisplay.js import React from 'react'; const CounterDisplay = <div> <h1>{this.state.counter}</h1> <button onClick={this.handleDecrement}>-</button> <button onClick={this.handleIncrement}>+ ...

Adding a sign at the center of a map in React-Leaflet

One of the features I added to the map is a center indicator sign. <MapContainer fullscreenControl={true} center={center} zoom={18} maxNativeZoom = {22} maxZoom={22} classNa ...

The attribute interface overload in Typescript is an important concept to

Consider a scenario where there are multiple payload options available: interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne ...

The messaging feature is not functioning properly within the page tab

The iframe page tab is not compatible with the Send dialog. I followed the example on the 'Send Dialog' page https://developers.facebook.com/docs/reference/dialogs/send/ <html xmlns:fb="https://www.facebook.com/2008/fbml"> <body> ...

Clicking on the LI element will automatically trigger a click event on the input radio button

Whenever I click on an li element, I want the corresponding radio input to be selected. However, when I try to do this, I'm seeing an error in the console log: Uncaught RangeError: Maximum call stack size exceeded How can I resolve this issue? Bel ...

Top method for saving information on page for Ajax calls

On my dynamically generated page, there is an array of data produced by php that I want to utilize for an ajax request. However, I am unsure of the best method to store this data on the page as it is not sensitive and does not involve a form. Currently, I ...

Can someone advise me on how to ensure my function effectively delivers a desired outcome?

My goal is to learn Javascript on my own, but I'm struggling to make progress. I've created a function called fixedSpending() that takes two inputs, num1 and num2, and adds them together. However, when the user hits the "=" button, I expect the f ...

What is preventing me from adding any style to this specific element?

Currently, I am in the process of creating a stopwatch for solving Rubik's cube. Within this project, there is a div element named "records" that is meant to display the time after a button is clicked. However, I am facing an issue where I am unable t ...

What is the best way to showcase database values in a text-box using retrieval methods?

I am currently working on a database project that involves a webpage with 5 textboxes. One of these textboxes needs to display values from the database when it is in focus. I have the JavaScript and AJAX code to retrieve the data, but I am facing difficult ...

I encountered an error while running a basic express app with ts-node-dev: Invalid argument: A non-string value was provided to `ts.resolveTypeReferenceDirective`

Recently, I started diving into Typescript and Express. Trying to set up a basic Express app using ts-node-dev, I encountered the following error: > ./node_modules/.bin/ts-node-dev src/index.ts 16:07:40 [I ...

What role does @next/react-dev-overlay serve in development processes?

Currently, I am diving into a NextJs project. Within the next.config.js file, there is this code snippet: const withTM = require('next-transpile-modules')([ 'some package', 'some package', 'emittery', ...