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.
test1will execute the function and print out 'Hi Johnandreturn undefined.t1will beundefined.test2will return a newfunctionwith a closure overtextand assign it tot2.t2is now a newfunction. You will need to execute it in order to get any output, which you haven't done yett2();