How are callback functions different from a helper function in javascript? if they are both accepting functions as arguments?
Callbacks are the functions that are passed as a function argument and are performed after a particular event such as resolving of a promise.
Helper functions are the normal functions that are called at any point of time when the code execution is taking place. Mostly, helper functions are wrapped inside another function.
Example of callback function:
const fun = (callback) => {
setTimeout(callback, 3000);
};
fun(() => {
console.log('callback function');
});
Example of helper function:
const factorialOfNNumbers = (...numbers) => {
const helperFact = (n) => {
if (n ===1 || n === 0)
return n;
return n * helperFact(n-1);
};
return numbers.map(n => helperFact(n));
};
console.log(factorialOfNNumbers(2, 3, 4));
They are both functions, but the difference I suppose is how they are referenced and/or used.
Helper functions are just called "whenever" when they are in scope. Callbacks are typically passed elsewhere and invoked with some parameters.
I hope the below snippet explains it.
// Just some function, what does it do?
const someFunction = (...args) => console.log("I'm a helper function", ...args);
const useAsHelperFunction = () => {
// Called directly
someFunction('used as helper function');
};
const useAsCallback = callback => {
// invoking callback
callback('used as callback function');
};
useAsHelperFunction();
useAsCallback(someFunction);
There nothing like callback function, it just refers to the function(named function) or anonymous function that is being called by a function or piece of code once it transitions to another state or after an event occurs.
Related
I wonder why this simple callback function (setTimout) gets called even though I didn't invoke but just assigned it.
In this code, I assinged setTimeout function to variable foo.
So I believe a returned value should be stored in variable foo
And It doesn't need to be executed and print 'hello' because I didn't call that function.
But why It gets called and print 'hello'?? What if I just want to assign and store it to variable??
Also How this function can be a number type and returned value is 2 ??
const foo = setTimeout(() => console.log('hello'), 2000);
// hello ( after 2 seconds )
console.log(typeof foo);
// number
console.log(foo);
// 2
Thanks in advance
To declare it a function to be called later:
const foo = function () {
setTimeout(() => console.log('hello'), 2000);
}
The return value of setTimeout is an integer Id for the timeout that can be used later with clearTimeout();
e.g.
var t = setTimeout(() => console.log('hello'), 2000);
// clear the time out
clearTimeout(t);
setTimeout invokes it. That's why it's called a callback. Another more common word for "invoke" is "call" so a callback is basically an invokeback: someone will invoke your code later.
Here's an example of code that accept a callback:
function foo (cb) {
// this function prints "foo" if callback returns true
if (cb()) { // foo() invoking cb()!
console.log('foo');
}
}
As you can see, the programmer who writes the function is the one who invokes/calls your function. You just need to define the function that they are going to call:
foo(function() { return true })
You just invoked the function with two parameters and stored the return result of setTimeout
const foo = setTimeout(() => console.log('hello'), 2000);//
Example:
I have a function setTimeout1
function setTimeout1(parm1, parm2){
// do somthing
return "Invoked";
}
const foo = setTimeout1(() => console.log('hello'), 2000);
in the following code
const express = require('express');
const app = express()
app.use(express.static('public'));
express is a function so how it call "express.static('public')" method on it? is it possible in JavaScript to call a function which is inside a function
A functions is not only a first class function, but also a first class object and can contain properties.
function foo() {}
foo.bar = function () { console.log('i am bar'); };
foo.bar();
You can attach a function as member data to another function (which is what is done in your example).
const express = () => {};
express.static = argument => console.log('argument');
express.static('public'); # console >>> 'public'
However, you cannot readily access a variable that is defined in a function body.
const express = () => {
const static = argument => console.log('argument');
};
express.static('public'); # console >>> Error: undefined in not a function
There is a signifiant difference between member data attached to a function (the first example) and the closure that wraps the body of the function (the second example).
So, to answer your question "is it possible in JavaScript to call a function which is inside a function?" No, this is not readily possible with the important note that this is not what is being done in your example.
Actually, it is possible to call a function inside another function in javaScript.
So it depends on the condition, Callback is widely used in js
(A callback is a function that is to be executed after another
function has finished executing)
function doHomework(subject, callback) {
alert(`Starting my ${subject} homework.`);
callback();
}
function alertFinished(){
alert('Finished my homework');
}
doHomework('math', alertFinished);
And the second example can be Closures
(A closure is a feature in JavaScript where an inner function has
access to the outer (enclosing) function's variables)
function outer() {
var b = 10;
function inner() {
var a = 20;
console.log(a+b);
}
return inner;
}
I originally come from the Java Programming language, and I was just wondering why it is possible in javascript to pass a callback function as a variable or plain object (without parameters) to another function, and then use this callback function inside of another function but this time with parameters to pass.
And how exactly is this callback returning my user object, as I did not specify a return function inside callback(user), or specify any function body at all for my callback. Is this done inside the setTimeout(()...) function as the timeoutHandler implementation is implicitly returning something?
var getUser = (id,callback) => {
var user = {
id: id,
name: 'Vikram'
};
setTimeout(() => {
callback(user);
},3000);
};
getUser(31, (userObject) => {
console.log(userObject);
});
I see two questions here:
why it is possible in javascript to pass a callback function as a variable or plain object (without parameters) to another function.
Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
Read more here: https://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
Below shows functions are just objects as well:
function hello() {
return 'hello';
}
hello.other = 'world';
console.log(hello() + ', ' + hello.other);
how exactly is this callback returning my user object, as I did not specify a return function inside callback(user), or specify any function body at all for my callback.
setTimeout(()...) function is not implicitly returning anything, it just registers a function, that would execute later. When the function registered by the setTimeout triggers, it invokes the callback(user) and that resolves getUser registered function which logs to the console. Remember callbacks are asynchronous.
Functions have implicit returns if not specified, which returns undefined, meaning you did not explicitly return.
Below shows an example:
function hello() {
console.log('Hello, World');
}
console.log(hello()); // undefined.
function hi() {
return 'Hi, World';
}
console.log(hi()); // Hi, World.
The function i.e callback is passed as reference here. So you can pass it as much you want, when you call it then you can pass on the arguments and it will refer to original function.
And also it's not returning the user object, it's just consoling out the user object. As you have not used any return it will return undefined. Try consoling the callback fn return out.
var getUser = (id,callback) => {
var user = {
id: id,
name: 'Vikram'
};
setTimeout(() => {
console.log(callback(user), 'return value of callback');
},3000);
};
In javascript function is a object.
It behaves like function only with ()
So you can pass function to another function or variable as value.
Some functions in javascript are asynchronous.
setTimeout is such async function. It means callback function will be run after a time.
What's happening:
//assign anonymous function to variable
// until function without () it only a object
var getUser = (id,callback) => {
//set up params
var user = {
id: id,
name: 'Vikram'
};
// setup asynchronous function setTimeout
setTimeout(() => {
// run callback with params when time would done
callback(user);
},3000);
};
// call function which contains in getUser-variable and pass 2 params: int and callback-function
getUser(31, (userObject) => {
console.log(userObject);
});
I'm brushing up on knowledge of Javascript and filling in some of the gaps.
for the memoize function, I get why it would console log the function as the memoizeSomeFunction const is just a function expression of someFunction being passed into memoize as an arg. what I can't seem to conceptualize is how the arg being passed into memoizeSomeFunction gets to the return part of the function. can someone elaborate?
const memoize = (fn) => {
console.log(fn);
return (arg) => {
console.log(arg)
}
}
const someFunction = (x = 0, y = 0) => {
return `x is {$x} y is ${y}`;
}
const memoizeSomeFunction = memoize(someFunction);
memoizeSomeFunction(1)
The memoize() function returns a function:
(...args) => {
console.log(...args)
}
That function collects its arguments into an array using the spread (...) syntax, and then un-collects them the same way in the console.log() call.
Thus when you call the function returned from memoize(), it simply logs the arguments passed.
To summarize:
Just one argument is passed to memoize(), your someFunction() function;
The memoize() function returns another function, and that function logs its arguments (and otherwise does nothing with someFunction());
The function source is logged when memoize() is called, and the argument list to the return value from that is logged whenever it is called. If you added another call to that returned function, you'd see those arguments logged separately.
// ES5 equivalent:
const memoize_es5 = function(fn) {
// fn is closured and can be used
// function returned, when it will be called we will have call arguments as well
return function () {
console.log(fn.apply(null, arguments));
}
}
const memoize = fn => (...args) => console.log(fn(...args));
const someFunction = (x = 0, y = 0) => {
return `x is ${x} y is ${y}`;
}
const memoizeSomeFunction = memoize(someFunction); // function received as result of memoize call
memoizeSomeFunction(1, 15); // pass arguments to that function function
// ...args in the arguments is a rest operator
// it just capture all rest arguments into an array:
((first, ...args) => console.log(first, args))(1, 2, 3)
// ...args in a function call is spread operator
// it spreads an array into parameter list:
console.log(...['spread', 'operator'])
I have two files in a folder - index.js and util.js with their code base as follows
Util.js
let obj = {}
obj.sendTransaction = () => {
console.log(arguments);
return new Promise((resolve, reject) => {
// try {
// let data = ethFunction.call()
// resolve(data)
// } catch (e) {
// reject(e)
// }
});
}
module.exports = obj
In Index.js, if I pass arguments to addNewParticipant or its variation then they do not turn up in the arguments object in util.js, for instance
const addNewParticipant = (foo, bar) => {
var ethFunction = myContract.addParticipant.sendTransaction
console.log(ethFunction);
EthUtil.sendTransaction()
}
const addNewParticipantTwo = (foo, bar) => {
var ethFunction = myContract.addParticipant.sendTransaction
console.log(ethFunction);
EthUtil.sendTransaction(ethFunction, foo, bar)
}
and call it such addNewParticpant(1, 2) and , addNewParticpantNew(1, 2) the numbers 1 and 2 do not show up in the arguments object in the util function. In fact, the arguments object remains the same, 4 inputs describing some functions and files in node_modules including Bluebird and a reference to index.js itself
My final aim is to
Pass a function from index.js to util.js
Pass along unknown number of variables
Call the passed function and apply the unknown number of variables to it
Wrap the whole thing in a promise and do some data validation
Ideally arguments[0] would represent a function I would pass and the other would be the values. I would then use
var result = arguments[0].apply(null, Array().slice.call(arguments, 1));
If it helps, the function I want to pass has an optional callback feature
As already mentioned in the comment, fat arrows don't have their own this or arguments objects. The arguments object you're logging is from the function created by the module loader, and its passed arguments.
You can either use a "regular function", or in this case, you can use a ...rest parameter
And, avoid the Deferred antipattern.
//first a little utility that might be handy in different places:
//casts/converts a value to a promise,
//unlike Promise.resolve, passed functions are executed
var promise = function(value){
return typeof value === "function"?
this.then( value ):
Promise.resolve( value );
}.bind( Promise.resolve() );
module.exports = {
sendTransaction(fn, ...args){
return promise(() => fn.apply(null, args));
}
}