Search This Blog

2024/03/24

What is Free Variable ?

Free variables are variables used in function that are neither locally declared
nor passed as parameter neither part of global scope.

Code:

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(); // 2

Output:
2

Explanation:

Here num is neither local variable w.r.t. function checkNumber()
nor variable passed to function checkNumber() as parameter.
Hence num is free variable w.r.t. checkNumber() function.

No comments:

Post a Comment