Q1 : Is this chain function exactly the same function with the parent one?
Q2 : The arguments are passed to parent function but it doesn’t has any parameter while chain function has rest operator ?
const sum = (function() {
"use strict";
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3));
1 Like
Hi @Nathanp
Q1: No. const
sum is a variable that stores a Self-Executing Anonymous Function. So we can call that function by sum()
. When that function is called it returns another function called sum with rest operator as function parameter. We should specify its parameters by providing arguments. So, at the beginning itself we have to provide the arguments to the chain function when we’re calling it.
For instance: sum(1,2,3);
Q2: The arguments are passed to the chained function.
You can check them by changing function’s name to add instead sum.
const sum = (function() {
"use strict";
return function add(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3)); //logs the same answer before!
Could you please explain Why would we need to call Self-Executing Anonymous Function by a variable it stores with again ? As i know so far it executes itself after (); outside its function scope.
" When that function is called, it returns another function called sum with rest operator as function parameter. We should specify its parameters by providing arguments " <<< Is this means we can pass argument to our chain function through parent function ?
Because console.log(sum(1, 2, 3));
sum(); itself means parent function but its arguments are sent to chain function ?
Yes.
We’re providing arguments to the parent function but the the parent function don’t have parameters. While the parent function executing it calls another function, that expects parameters so the arguments are passed there.
The parent function’s scope includes child functions, so the child can access them. link
1 Like
I think may be to pass the arguments.
Like: sum(1, 2, 3);
1 Like
Can you clarify my doubts, Chain function can automatically takes parameters from its parent function as long as parent function has a parameter to receive argument. yeah that makes sense. just like this code below
function fn1(pam1) {
function fn2() {
console.log('this is sent from ' + pam1 );
}
fn2();
}
fn1('parent function');
*** But… **** this code
const sum = (function() {
"use strict";
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3));
The parent function doesn’t even has parameter, How it’s even possible to passing argument to the Chain function ?