Reputation: 3347
I am studying JS and the concept of closures.
In the code below the inner child function looks for values for num and num1. Next the interpreter goes up the scope chain searching for them. It looks in main() and doesn't see them so it goes on up to main's arguments where it doesn't see them in the declaration, but they are in the invocation. That's where it gets them from. That's my understanding of how this code works, is that correct?
Thanks
function main() {
return function child(num, num1) {
console.log(num + num1);
}
}
const result = main();
result(2, 4); // return 6
Upvotes: 2
Views: 177
Reputation: 32175
There's no closure here.
What you are doing is that you are creating a function
that returns another function
.
And in your line:
const result = main();
You are storing this inner function
inside a variable
. Then you are calling it with two params in the line:
result(2, 4);
Demo:
Please check this demo, and how the inner function is stored inside the variable, then called.
function main() {
return function child(num, num1) {
console.log(num + num1);
}
}
//Store inner function in a variable
let innerFn = main();
console.log(innerFn);
console.log(typeof innerFn);
//Then call this function
innerFn();
innerFn(10, 4);
Upvotes: 1
Reputation: 36660
Your arguments stay within the scope of your function. When the JS engine encounters an identifier it will first look in the scope (arguments and variables) of the function it is currently executing. If it doesn't find that variable there it will go up the scope chain until it reaches the global scope. If it doesn't find it, it will throw a reference error.
For example:
let foo = 1;
let bar = 2;
function test () {
let foo = 5;
console.log(foo, bar);
}
test();
In this example foo is overwritten by the new foo created inside the function. The JS engine gets the value of bar by climbing the scope chain.
A closure captures the environment of the function when the function is created for example:
function higher (value) {
let el = value
return () => console.log(el);
}
const first = higher(5)
const second = higher(2);
first();
second();
Upvotes: 1
Reputation: 944430
There is no practical difference (at least within the scope of your question) between:
function name (foo) {
}
and
function name () {
var foo = arguments[0];
}
It is just two ways to create a variable scoped to a function.
So it doesn't look for for a variable declaration in the body and then for one in the arguments if it doesn't find one. It just looks for a variable in the scope of the function.
Upvotes: 1