Mauro Alvarez
Mauro Alvarez

Reputation: 612

Understanding closure scope in JavaScript

I've been reading the "You Don't Know JS" book series and I have a question regarding closures.

var a;

function wait() {
  a = 10;

  return setTimeout(function timer() {
    console.log('Hello closure ', a);
  }, 1000)
}

const fn = wait;
fn();
console.log(a);

If I asked for the value of a in the console without executing the function (fn()), it will say it is undefined which is correct.

Now if I execute the function fn() after 1 second it will print Hello Closure 10 I know that timer has a closure over wait function, that's why it prints that value, even when it is executed outside the lexical scope where it was defined.

But if a print a value in the console now (after running fn()) it output also 10 , so I guess this is not lexical scope, from global scope the lookup never goes down (I mean it looks deep down in the nested functions), it always look for the variables up (going up to the enclosing scopes of functions).

So I wonder if this is closure too or the variable just got another value after running the function and that's all?

Upvotes: 0

Views: 48

Answers (1)

pmkro
pmkro

Reputation: 2550

If you instantiate the variable inside the function, it will prevent global variables of the same name from changing. I added a var a = 10 into the function. I left the globally scoped var there so you can see that now it doesn't change. This is more of a variable scoping issue.

The closure was working as you expected, just you were setting a global variable.

var a;
function wait() {
  var a = 10;

  return setTimeout(function timer() {
    console.log('Hello closure ', a);
  }, 1000)
}

const fn = wait;
fn();
console.log(a);

Upvotes: 1

Related Questions