-1

I am reading a tutorial about javascript closure.There is a concept called free variables.Free variables are variables that are neither locally declared nor passed as a parameter.

The tutorial's first example:

function numberGenerator() {
  // Local “free” variable that ends up within the closure
  var num = 1;
  function checkNumber() { 
    console.log(num);
  }
  num++;
  return checkNumber;
}

var number = numberGenerator();
number();

In this example, the comment said num is a local free variable.But the above concept about free variable said a free variable is not locally declared.I am confusing about that.

ChenLee
  • 1,371
  • 3
  • 15
  • 33

3 Answers3

0

The right term in this case is a locally declared variable (local to the numberGenerator()).

This definition could help you to understand a closure:

A closure is the local variables for a function - kept alive after the function has returned.

GibboK
  • 71,848
  • 143
  • 435
  • 658
0

Not sure what you question is but num is only availible within the closure its considered a "private" variable of numberGenerator.

Pascal L.
  • 1,261
  • 9
  • 21
0

So num is a local to the numberGenerator() function. If you try to access or use it outside of this function, it would return an error. Check the below code, at the last line, I have console.log() and used num but it throws an error and doesn't give any value, that's because num is local to numberGenerator() function and can be used only inside it:

function numberGenerator() {
  // Local “free” variable that ends up within the closure
  var num = 1;
  console.log('Value inside numberGenerator: ' + num);

  function checkNumber() {
    console.log('Value inside checkNumber: ' + num);
  }
  num++;
  return checkNumber;
}

var number = numberGenerator();
number(); // 2
console.log('Callling from outside functions: ' + num);
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35