0

I ran the code below, and the first alert was alert 'a.' After I clicked o.k., alert 'b' popped up immediately, but I don`t understand how this all worked.

Since a() is assigned to var newFunc, when I hit enter after newFunc();, it runs function a(), and function a() returns an anonymous function, but how does this anonymous function get called so that alert('B') pop up appears after I clicked o.k. on the alert A pop up?

function a(){
  alert ('A');
  return function() {
    alert('B');
  };
}    

var newFunc = a();
newFunc(); 
mjmitche
  • 2,077
  • 5
  • 24
  • 31

2 Answers2

2

Function a gets calles with a() alerting 'A'. It returns an anonymous function, which is then stored in the variable newFunc. Why? Because you assigned it: var newFunc = a();

You could then think of newFunc as:

var newFunc = function() {
    alert('B');
};

Then you call the returned function with newFunc(). It alerts 'B'.

This is called a closure. Check out more about closures, they are pretty awesome.

Community
  • 1
  • 1
David
  • 3,392
  • 3
  • 36
  • 47
  • if newFunc() calls the closure function alerting B, how does the function get called the first time? when you say "function a gets called with a()", which code makes that call? is it also newFunc()? so newFunc() calls both a() and the return function? please explain if you can. thanks for your help. – mjmitche Mar 18 '11 at 06:48
  • Let's have a look at both your last lines. The first of them says `var newFunc = a();`. You assign the return value of the function `a` – which is called at the time you write `a()` – to the variable `newFunc`. Since `a()` returnes a function, newFunc now stores a function. Second line: You call the new function with `newFunc();`. – David Mar 18 '11 at 06:51
2

after first call

var newFunc = a();//alerts A

function a() executed and it's return value is another function, that was written to variable newFunc

newFunc();//alerts B

newFunc is a variable with type function so it can be executed ( and alert "B" )

Dmitry Evseev
  • 11,533
  • 3
  • 34
  • 48
  • It`s not clear to me. Are you saying that var newFunc is first assigned a() and then, after the function is returned, newFunc gets assigned that return function, which alerts B? – mjmitche Mar 18 '11 at 06:50