Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does closures work in Javascript when we return a function?

Tags:

javascript

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 save them to vars,

var t1 = test1('John');
var t2 = test2('John');

What is exactly happening here?

like image 475
siwalikm Avatar asked Jul 25 '26 20:07

siwalikm


1 Answers

Lets understand this:

In below code you are defining a function called test1 which will print Hi, John if you use test1('John').

test1 = function(name){
    console.log('Hi, ', name);
};

Now lets 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 called text
  • var say = function() { console.log(text); } //defininga a function called say which will log the data in variable text in the console.
  • Then you are returning say function.

OUTPUT:
Input: => var t1 = test1('John');
Output: => Hi, John //It's quite straight forward.

Input: => var t2 = test2('John');
Output: => undefined //Here you are re-assigning function returned from test2 which was say to t2. Hence if you now type t2 then you wil get function () { console.log(text); } as output which is similar to say.

I hope you understood, sorry for poor english.

like image 96
Kung Fu Panda Avatar answered Jul 27 '26 08:07

Kung Fu Panda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!