Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as an argument in a javascript function

Tags:

javascript

I was wondering whether this is legal to do. Could I have something like:

function funct(a, foo(x)) {   ... } 

where a is an array and x is an integer argument for another function called foo?

(The idea is to have one function that uses a for loop on the array, and calls that function in the params for every element in the array. The idea is so call this on different functions so elements of two arrays are multiplied and then the sums are added together. For example A[0] * B[0] + A[1] * B[1].)

like image 690
Spence Avatar asked Apr 22 '11 03:04

Spence


People also ask

Can you pass a function as an argument JavaScript?

Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.

Can we pass a function as an argument to a function?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.

How do you pass this function in JavaScript?

You can use addEventListener to pass this to a JavaScript function.

What does it mean to pass a function as an argument?

Functions are data, and therefore can be passed around just like other values. This means a function can be passed to another function as an argument. This allows the function being called to use the function argument to carry out its action. This turns out to be extremely useful.


1 Answers

I think this is what you meant.

funct("z", function (x) { return x; });  function funct(a, foo){    foo(a) // this will return a  } 
like image 57
Sergei Golos Avatar answered Oct 14 '22 17:10

Sergei Golos