0

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?

2
  • 4
    Its value is staying as 10 because you set the variable in the global scope. Commented Mar 29, 2019 at 17:58
  • function wait() { var a = 10; ... ` would be different... Commented Mar 29, 2019 at 18:00

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.