I am new to JavaScript and have several questions about functional programming.
Here is a statement:
outer(inner(5));
Is it possible to construct function outer in a way that allows it
to capture function inner and its argument 5?
Is it possible to construct function inner in a way that allows it to
pass itself and its argument 5 to function outer?
If the answer to both questions above is no, is it possible to
construct functions outer and inner in a way that allows the former
to capture function inner and its argument 5 or the
latter to pass itself and its argument 5 to function
outer?
I tried:
using the arguments object but to no avail.
function outer (parameter) {
return arguments;
}
function inner (n) {
return n + 1;
}
console.log(outer(inner(5))); // returns Arguments { 0: 6 ... }
using currying but I do not see how it can help me since I am not given the following statement:
outer()(5);
A possible workaround consists in returning an array from inner() composed of on one side the processing function and on the other side the argument.
outer will be able to access both by reading the array.
function outer(arr)
{
var fun = arr[ 0 ];
var arg = arr[ 1 ];
var result = fun(arg);
console.log('inner function is:', fun);
console.log('its argument is:', arg);
console.log('its result is:', result);
return result;
}
function inner(num)
{
return [
function (_num)
{
return _num + 1;
},
num
]
}
console.log(outer(inner(5)));
You could achieve this by letting your inner return a function (foo) which closes over n. You can then let foo return n+1. Then, within your outer function, you can invoke foo to get its return value:
const outer = f => f();
const inner = n => _ => n+1;
console.log(outer(inner(5)));
Alternatively, another possibility would involve changing your return value. You could return an array from inner which contains the original passed through arguments (...arguments) and the returned value (to_return) and then use destructuring assignment to get the passed in argument(s) (n & m) and the returned result:
function outer([result, n, m]) {
console.log("returned from inner: ", result);
console.log("arguments passed into inner: " + [n, m]);
return n;
}
function inner(n, m) {
let to_return = n + 1;
return [to_return, ...arguments];
}
console.log(outer(inner(5, 2))); // returns 5
Note: I added an m argument to demonstrate how you can extend this to multiple arguments
function outer(myFunction, argument) {
if (typeof myFunction !== "function") {
return false;
}
return myFunction(argument);
}
function inner(n) {
return n + 1;
}
console.log(outer(inner, 5));
Just a simple approach. Don’t execute the function inner but pass it as an argument (myFunction). And let the outer function execute it with the given argument.
i have trouble with the following code:
var placeingOrders = function(orderNumber) {
console.log("Order number: ", orderNumber);
requestedOrder(orderNumber, returnOrder);
};
function requestedOrder(orderNumber, callback) {
setTimeout(orderNumber, callback, 5000);
}
function returnOrder() {
console.log("Order number: " , " is delivered");
}
im trying to pass arguments on callback function but when i do as above i got the following error code:
timers.js:348
throw new TypeError('"callback" argument must be a function');
^
TypeError: "callback" argument must be a function
at exports.setTimeout (timers.js:348:11)
And of course if i run the same code without arguments it will work.
var placeingOrders = function(orderNumber) {
console.log("Order number: ", orderNumber);
requestedOrder(returnOrder);
};
function requestedOrder(callback) {
setTimeout(callback, 5000);
}
function returnOrder() {
console.log("Order number: " , orderNumber , " is delivered");
}
I would like to know what im exactly doing wrong here. How do i use this callback function correctly if i want to pass arguments.
(ps: im not a native english speaker, sry for that)
Why you get this error ?
setTimeout expects to get the callback function as the first argument, but at the first place you pass a number, so why the exception. The second case works, because you remove the orderNumber from the first place, an the function gets it.
You need to pass the arguments of the callback function after the 2nd place. See the setTimeout function signature. First goes the callback function, 2nd - the time, at least to call the function and after it everything which are passed goes to the callback function as arguments.
This is the signature of the function - [] are optional ones.
setTimeout(function[, delay, param1, param2, ...])
Code
var placeingOrders = function(orderNumber) {
console.log("Order number: ", orderNumber);
requestedOrder(orderNumber, returnOrder);
};
function requestedOrder(orderNumber, callback) {
setTimeout(callback, 5000, orderNumber);
}
function returnOrder(orderNumber) {
console.log("Order number: " + orderNumber + " is delivered");
}
placeingOrders(14);
I am a beginner to JS world, and I have a question.
when I was studying .forEach() javascript function, I noticed that it takes 2 parameters, the first is a function and the second is the value of This obj and the normal usage like this:
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}
// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
but I noticed also that it can be called also like this:
example num 2 :
[2, 5, , 9].forEach(function(){
console.log(arguments);
});
if .forEach() function takes a callback function as a parameter, how the second example is correct because it takes a function definition not a reference to a function which will be called,
I mean why it accepts a function definition in the second example although it takes a defined function name?
I mean also that forEach need a reference to a function only, so when it loops on each element, it will just add () to the function reference so the function will be called
function definition in javascript returns pointer to that function. You can also go through syntax like
let myFunction = function() { ... } // define function and save it into variable
myFunction() // call the defined function
So passing function by name and passing function definition is same thing
In the second example, the parameter is an anonymous function as compared to first where you defined the function first and used it's reference to pass to .forEach(). So, both are essentially same. You can also write second example like
[2, 5, , 9].forEach(function(element, index, array){
//do something with element
});
If you take a look at Polyfill what it does is it first check if the type of passed callback is a function and if it isn't then it throws an error, otherwise it uses call() to invoke that function so it doesn't matter if its anonymous function or function declaration.
It also checks if number of passed arguments is > 1 or if there is one more parameter after callback and you can access that parameter with this in your callback.
function invoke(callback) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) var Obj = arguments[1];
var value = 1;
callback.call(Obj, value);
}
invoke(function(e) {
console.log(this)
console.log(1 + e)
}, {foo: 'bar'})
var another = function(e) {
console.log(10 + e)
}
invoke(another);
to reach to the correct answer you have to:
read the correct marked answer comments (the last comment), then read the answer Nenad Vracar as both of them covered my missed approaches, thanks for both of them.
I'm trying to pass some parameter to a function used as callback, how can I do that?
This is my try:
function tryMe(param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester(callback, param1, param2) {
callback(param1, param2);
}
callbackTester(tryMe, "hello", "goodbye");
If you want something slightly more general, you can use the arguments variable like so:
function tryMe(param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester(callback) {
callback(arguments[1], arguments[2]);
}
callbackTester(tryMe, "hello", "goodbye");
But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)
This would also work:
// callback function
function tryMe(param1, param2) {
alert(param1 + " and " + param2);
}
// callback executer
function callbackTester(callback) {
callback();
}
// test function
callbackTester(function() {
tryMe("hello", "goodbye");
});
Another Scenario :
// callback function
function tryMe(param1, param2, param3) {
alert(param1 + " and " + param2 + " " + param3);
}
// callback executer
function callbackTester(callback) {
//this is the more obivous scenario as we use callback function
//only when we have some missing value
//get this data from ajax or compute
var extraParam = "this data was missing";
//call the callback when we have the data
callback(extraParam);
}
// test function
callbackTester(function(k) {
tryMe("hello", "goodbye", k);
});
Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester (callback) {
callback();
}
callbackTester(tryMe.bind(null, "hello", "goodbye"));
You can also use the following code, which adds the method if it isn't available in the current browser:
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
Example
bind() - PrototypeJS Documentation
If you are not sure how many parameters are you going to be passed into callback functions, use apply function.
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester(callback,params){
callback.apply(this,params);
}
callbackTester(tryMe,['hello','goodbye']);
When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).
function login(accessedViaPopup) {
//pass FB.login a call back function wrapper that will accept the
//response param and then call my "real" callback with the additional param
FB.login(function(response){
fb_login_callback(response,accessedViaPopup);
});
}
//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
//do stuff
}
Wrap the 'child' function(s) being passed as/with arguments within function wrappers to prevent them being evaluated when the 'parent' function is called.
function outcome(){
return false;
}
function process(callbackSuccess, callbackFailure){
if ( outcome() )
callbackSuccess();
else
callbackFailure();
}
process(function(){alert("OKAY");},function(){alert("OOPS");})
Code from a question with any number of parameters and a callback context:
function SomeFunction(name) {
this.name = name;
}
function tryMe(param1, param2) {
console.log(this.name + ": " + param1 + " and " + param2);
}
function tryMeMore(param1, param2, param3) {
console.log(this.name + ": " + param1 + " and " + param2 + " and even " + param3);
}
function callbackTester(callback, callbackContext) {
callback.apply(callbackContext, Array.prototype.splice.call(arguments, 2));
}
callbackTester(tryMe, new SomeFunction("context1"), "hello", "goodbye");
callbackTester(tryMeMore, new SomeFunction("context2"), "hello", "goodbye", "hasta la vista");
// context1: hello and goodbye
// context2: hello and goodbye and even hasta la vista
Use curried function as in this simple example.
const BTN = document.querySelector('button')
const RES = document.querySelector('p')
const changeText = newText => () => {
RES.textContent = newText
}
BTN.addEventListener('click', changeText('Clicked!'))
<button>ClickMe</button>
<p>Not clicked<p>
Faced this recently, to get it(especially if the parent function has multiple arguments doing different stuffs not related to the callback , is to have the callback placed with its argument in an arrow function passed as an argument.
function tryMe(param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester(callback, someArg, AnotherArg) {
callback();
}
callbackTester(()=> tryMe("hello", "goodbye"), "someArg", "AnotherArg");
...or simply if you dont have multiple arguments doing other stuff.
function tryMe(param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester(callback) {
callback();
}
callbackTester(()=> tryMe("hello", "goodbye"));
A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.
For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.
someObject.doSomething(param1, function(result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function(result2) {
console.log("Got result from doSomethingElse: " + result2);
}, function(error2) {
console.log("Got error from doSomethingElse: " + error2);
});
}, function(error1) {
console.log("Got error from doSomething: " + error1);
});
Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:
someObject.doSomething(param1, function (result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function (result2) {
console.log("Got result from doSomethingElse: " + result2);
}, handleError.bind(null, "doSomethingElse"));
}, handleError.bind(null, "doSomething"));
/*
* Log errors, capturing the error of a callback and prepending an id
*/
var handleError = function (id, error) {
var id = id || "";
console.log("Got error from " + id + ": " + error);
};
The calling function will still add the error parameter after your callback function parameters.
Let me give you a very plain Node.js style example of using a callback:
/**
* Function expects these arguments:
* 2 numbers and a callback function(err, result)
*/
var myTest = function(arg1, arg2, callback) {
if (typeof arg1 !== "number") {
return callback('Arg 1 is not a number!', null); // Args: 1)Error, 2)No result
}
if (typeof arg2 !== "number") {
return callback('Arg 2 is not a number!', null); // Args: 1)Error, 2)No result
}
if (arg1 === arg2) {
// Do somethign complex here..
callback(null, 'Actions ended, arg1 was equal to arg2'); // Args: 1)No error, 2)Result
} else if (arg1 > arg2) {
// Do somethign complex here..
callback(null, 'Actions ended, arg1 was > from arg2'); // Args: 1)No error, 2)Result
} else {
// Do somethign else complex here..
callback(null, 'Actions ended, arg1 was < from arg2'); // Args: 1)No error, 2)Result
}
};
/**
* Call it this way:
* Third argument is an anonymous function with 2 args for error and result
*/
myTest(3, 6, function(err, result) {
var resultElement = document.getElementById("my_result");
if (err) {
resultElement.innerHTML = 'Error! ' + err;
resultElement.style.color = "red";
//throw err; // if you want
} else {
resultElement.innerHTML = 'Result: ' + result;
resultElement.style.color = "green";
}
});
and the HTML that will render the result:
<div id="my_result">
Result will come here!
</div>
You can play with it here: https://jsfiddle.net/q8gnvcts/ - for example try to pass string instead of number: myTest('some string', 6, function(err, result).. and see the result.
I hope this example helps because it represents the very basic idea of callback functions.
function tryMe(param1, param2) {
console.log(param1 + " and " + param2);
}
function tryMe2(param1) {
console.log(param1);
}
function callbackTester(callback, ...params) {
callback(...params);
}
callbackTester(tryMe, "hello", "goodbye");
callbackTester(tryMe2, "hello");
read more about the spread syntax
I'm trying to pass some parameter to a function used as callback, how can I do that?
I think he is implying that he wants to call the function this callbackTester(tryMe, "hello", "goodbye"). To do this we can use the Rest Operator (...). This operator takes the arguments that a function receives and dumps them into a real array that we will use to access in our callback function.
Now, some other developers might also argue that we could use the arguments "array". That will be fine, but we should be careful with it. arguments is not a real array but an array-like object with a length property.
Here is a working snippet using the Rest Operator:
function tryMe(params) {
console.log(params.join(', '));
}
function callbackTester(callback, ...params) {
callback(params);
}
callbackTester(tryMe, 'hello', 'goodbye', 'hi again');
callbackTester(tryMe, 'hello', 'goodbye');
callbackTester(tryMe, 'hello');
Just use the bind() function which is primarily used to set the this value. However, we can also use it to pass parameters without calling the function due to bind() returning a new function with the sequence of arguments provided.
Example:
function foo(param1, param2, param3) {
console.log(param1, param2, param3);
}
setTimeout(foo.bind(null, 'foo', 'bar', 'baz'), 1000);
In the snippet above, the setTimeout function takes 2 arguments, the callback function and a minimum time in ms for the function to be called, so when passing the callback function we're going to use bind and specify the parameters
Note: The first parameter of bind is the value that we want to set for this, and because we're not interested on that, null was passed, the subsequent parameters in bind are going to be the parameters for the callback.
I was looking for the same thing and end up with the solution and here it's a simple example if anybody wants to go through this.
var FA = function(data){
console.log("IN A:"+data)
FC(data,"LastName");
};
var FC = function(data,d2){
console.log("IN C:"+data,d2)
};
var FB = function(data){
console.log("IN B:"+data);
FA(data)
};
FB('FirstName')
Also posted on the other question here
//Suppose function not taking any parameter means just add the GetAlterConfirmation(function(result) {});
GetAlterConfirmation('test','messageText',function(result) {
alert(result);
}); //Function into document load or any other click event.
function GetAlterConfirmation(titleText, messageText, _callback){
bootbox.confirm({
title: titleText,
message: messageText,
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
return _callback(result);
}
});
This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 6 years ago.
I want to something similar to this:
function AjaxService()
{
this.Remove = function (id, call_back)
{
myWebService.Remove(id, CallBack)
}
function CallBack(res) {
call_back(res);
}
}
so my calling program will be like this:
var xx = new AjaxService();
xx.Remove(1,success);
function success(res)
{
}
Also if I want to add more parameters to success function how will I achieve it.
Say if I have success function like this:
var xx = new AjaxService();
//how to call back success function with these parameters
//xx.Remove(1,success(22,33));
function success(res,val1, val2)
{
}
Help will be appreciated.
Use a closure and a function factory:
function generateSuccess (var1,var2) {
return function (res) {
// use res, var1 and var2 in here
}
}
xx.Remove(1,generateSuccess(val1,val2));
What you're passing here is not the generateSuccess function but the anonymous function returned by generateSuccess that looks like the callback expected by Remove. val1 and val2 are passed into generateSuccess and captured by a closure in the returned anonymous function.
To be more clear, this is what's happening:
function generateSuccess (var1,var2) {
return function (res) {
// use res, var1 and var2 in here
}
}
var success = generateSuccess(val1,val2);
xx.Remove(1,success);
Or if you prefer to do it inline:
xx.Remove(1,(function(var1,var2) {
return function (res) {
// this is your success function
}
})(val1,val2));
not as readable but saves you from naming the factory function. If you're not doing this in a loop then Xinus's solution would also be fine and simpler than my inline version. But be aware that in a loop you need the double closure mechanism to disconnect the variable passed into the callback function from the variable in the current scope.
You can pass it as anonymous function pointer
xx.Remove(1,function(){
//function call will go here
success(res,val1, val2);
});
one way to do this:
function AjaxService {
var args_to_cb = [];
this.Remove = function (id, call_back, args_to_callback_as_array) {
if( args_to_callback_as_array!=undefined )
args_to_cb = args_to_callback_as_array;
else
args_to_cb = [];
myWebService.Remove(id, CallBack)
}
function CallBack(res) {
setTimeout( function(){ call_back(res, args_to_cb); }, 0 );
}
}
So you can use it like this:
var service = new AjaxService();
service.Remove(1,success, [22,33]);
function success(res,val1, val2)
{
alert("result = "+res);
alert("values are "+val1+" and "+val2);
}
I usually have the callback execute using a setTimeout. This way, your callback will execute when it gets the time to do so. Your code will continue to execute meanwhile, e.g:
var service = new AjaxService();
service.remove(1, function(){ alert('done'); }); // alert#1
alert('called service.remove'); // alert#2
Your callback will execute after alert#2.
Of course, in case of your application, it will happen so automatically since the ajax callback itself is asynchronous. So in your application, you had better not do this.
Cheers!
jrh