Home > database >  Question regarding closures? Is this a form of pseudo-closure, if so, why use function closures over
Question regarding closures? Is this a form of pseudo-closure, if so, why use function closures over

Time:10-07

I am currently learning JS trying to understand closures and their uses. I understand they are useful to avoid polluting the global scope, but then I realised, isn't the code below basically the same as a closure without using a function? I am not sure if I have missed the point of closures so if someone with more knowledge could verify is this is a closure, and if so, why using a function is better.

log = console.log;
dir = console.dir; 
{
  let x = 0;

  function testFunc() {
    log(  x);
  }
}

let func = testFunc;
testFunc();

CodePudding user response:

I suppose you're comparing your code with something like this:

log = console.log;

let func = function() {
  let x = 0;

  function increment() {
    log(  x);
  }
  return increment;
}();

func();
func();

Your code is indeed equivalent. The older style was used before let variable declarations were added to JavaScript in EcmaScript 2015 (AKA EcmaScript 6). That added the ability to create variables that are scoped to a block, rather than a whole function.

If you change your version to use var x = 0;, the x variable pollutes the global scope.

The other reason that closures are usually inside other functions is so that you can create a dynamic number of them.

function create_counter(start = 0) {
  return function() {
    return start  ;
  }
}

counter1 = create_counter();
counter2 = create_counter(5);
console.log(counter1());
console.log(counter1());

console.log(counter2());
console.log(counter2());

  • Related