0

I have a simple question about Javascript Closures:

The following function is given:

function outside() {
  var out = 0;
    function inside() {
    out +=1;
    }
  return inside;
} 

var ref = outside();
ref();  
ref();

If I call the function 2 times, out is equal to 2.

Why is out not overwritten by the statement?

var out = 0;
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
AndyB
  • 391
  • 2
  • 4
  • 17
  • I think the best way to understand it is to experience it. Make a test page (or fiddle) with this code, then go through it, step by step, using your browser's debugger. – Volune Aug 16 '14 at 22:12

2 Answers2

1

The statement var out = 0 is not inside the function returned from outside(). It only runs when you call outside() not when you call ref() (which is the same as inside()).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

outside() returns inside. So ref = inside. When you call ref(), it's like calling inside().

inside has the scope of outside, which contains out. When you call ref(), it increments the out property on the single scope of outside.

Tucker Connelly
  • 865
  • 1
  • 8
  • 17