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?

+3


source to share


4 answers


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 named text

  • var say = function() { console.log(text); }

    // definition of a function with a name say

    that will write data to a variable text

    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.

+2


source


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

+2


source


When called, test2 returns "say", which is a function pointer, not a value. That's why it doesn't output anything. To call the "say" function you need to do test2('john')()

. In the second pair of parentheses, we pass the arguments to the function inside.

+1


source


your first function executes the code and returns nothing, then t1 will be undefined. but the second function returns a function, then t2 contains a function that has never been called, so it will not enter the console

+1


source







All Articles