both function print the value inside the "outer" and "inner" function twice.
using simple function declaration & execution
function outer1() {
var j = 20;
function inner1() {
var k = 30;
console.log(j, k);
j++;
k++;
}
inner1(); //calling inner1
return;
}
outer1(); // calling function 2 times
outer1();
output : // same output both time
20 30
20 30
-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x//
using function expression
function outer() {
var a = 20;
var inner = function() {
var b = 30;
console.log(a, b);
a++;
b++;
}
return inner; //returning inner
}
var func = outer();
func(); // calling function 2 times
func();
output : // value of a is incremented by 1 time.
20 30
21 30
I am confused, why both are showing different result ?, why output remain same for the first one but different for second one ?
With the first example, you run outer() multiple times. This creates a new inner function each time, each with the initial value of j.
If you're familiar with classes, this is kind of like calling new Thing().do(); new Thing().do(); vs const thing = new Thing(); thing.do(); thing.do();