Lets say, I have defined a function like
var f = function(cb){cb()};
Now, if I pass a callback function it will work:
f(()=>{console.log("ccb")}); //print: ccb
But if I pass a argument, in this case x will be undefined:
f((x)=>{console.log("x:"+x);}); // x will be undefined
so one solution is to use closure,
function cba(x){
return function(){
console.log("ccbbaa:"+x)
}
}
f(cba(20)); //will work give output: ccbbaa:20
But if I am trying to achieve closure using inplace function, considering xx is defined.
var xx = 20;
f(function(xx){
return function(){
console.log("xxx: "+xx)
}
});
callback inside f is not even called. Why? How will we can use this inline function to make it work? I am studying closures so wanted to understand this. Any help is appreciated.
function(xx)which returns a new function with signaturefunction()but you never execute the latter. Since it's also never returned, you can't invoke it afterwards, either. It's just produced and at some point garbage collected.f()doesn't do anything with the return value it gets from calling the function passed to it.fto do somethingfisn't designed to do at all and are approaching it by changing what you pass tof… but no matter what you pass tofit isn't going to change howfworks.