How does closure work in Javascript on function return?
Suppose I have two functions test1 and test2!
test1 = function(name){
console.log('Hi, ', name);
};
test2 = function(name) {
var text = 'Hello ' + name;
var say = function() { console.log(text); }
return say;
}
Now I call the function and store it in vars,
var t1 = test1('John');
var t2 = test2('John');
What's going on here?
source to share
Let's take a look at this :
In the code below, you define a function named test1
that will print Hi, John
if you use test1 ("John").
test1 = function(name){
console.log('Hi, ', name);
};
Now let's understand below code below, you are defining a function called test2
which:
test2 = function(name) {
var text = 'Hello ' + name;
var say = function() { console.log(text); }
return say;
}
-
var text = 'Hello ' + name;
// define a variable namedtext
-
var say = function() { console.log(text); }
// definition of a function with a namesay
that will write data to a variabletext
in the console. - Then you return the function
say
.
OUTPUT:
Input: => var t1 = test1('John');
Output: => Hi, John
// This is pretty straight forward.
Input: => var t2 = test2('John');
Output: => undefined
// This is where you re-assign the function returned from test2
which was say
in t2
. Hence, if you type now t2
then you will get function () { console.log(text); }
as output which is similar to say
.
I hope you understand, sorry for the bad english.
source to share
Your function test1
returns void as there is no statement return
This function prints Hi John
to the console
Your function test2
returns the function say()
to the console and stores it in t2
. This makes the function a t2
function. If you notice the syntax in test2
, that's one of the two standard ways to define a function in javascript. if you call
t2();
you get similar output in test1('John');
:
Hello John
source to share