Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - add parameters to a function passed as a parameter

Here is the behaviour I'm looking for:

function one(func){
   func(5);
}

function two(arg1, arg2){
   console.log(arg1);
   console.log(arg2);
}

one(two(3)) //prints 3, 5

Can this behaviour or something similar be accomplished in javascript?

like image 774
Adam Griffiths Avatar asked Feb 02 '17 12:02

Adam Griffiths


People also ask

Can we pass function as a parameter in JavaScript?

Conclusion. 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.

How do you add a parameter to a function?

Parameters are specified within the pair of parentheses in the function definition, separated by commas.

How do you pass a function as a parameter?

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. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

What happens if you pass an extra parameter to a method in JavaScript?

Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.


3 Answers

You can always use the bind() function to pass some arguments to your function. It'll create a new function with the first argument - arg1 - equal to the value of 3 in this example:

function one(func){
   func(5);
}

function two(arg1, arg2){
   console.log(arg1);
   console.log(arg2);
}

one(two.bind(null, 3))

You can read more about the bind() function here: MDN - Bind

like image 106
Mateusz Kleinert Avatar answered Oct 18 '22 23:10

Mateusz Kleinert


Some workaround is possible

function one() {

  var args = Array.prototype.slice.call(arguments);
  var func = args[0];
  args.splice(0, 1);
  args.push(5);
  func.apply(this, args);
}

function two(arg1, arg2) {
  console.log(arg1);
  console.log(arg2);
}

one(two, 3)
like image 27
Nikhil Aggarwal Avatar answered Oct 18 '22 23:10

Nikhil Aggarwal


There's a problem with your syntax: function one is expecting its single argument to be a function. Then, below, when you invoke it, you are not passing the function two, but whatever two returns when it's passed a single argument, probably undefined. I don't know what specifically you're trying to accomplish but I'd recommend a little research into closures.

like image 26
MrFarberToYou Avatar answered Oct 18 '22 22:10

MrFarberToYou