DEV Community

Cover image for Hoisting with closures example
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

2

Hoisting with closures example

Try guessing what is the output of the following snippet:

function one() {
  function two() {
    console.log(`closure var1 - ${var1}`);
  }

  three();
  var var1 = 'var1';   
}

one();
Enter fullscreen mode Exit fullscreen mode


It yields hoisting var1 - undefined, because of hoisting of var1 variable (it is allocated in memory with value undefined), but it is not initialised with the value var1 by the time the closure is executed.

But, if we use setTimeout(), by the time the callback closure function is executed var1 will have been initialised and its value is printed:

function one() {
 setTimeout(function() {
  console.log(`closure var1 - ${var1}`);
 }, 0);
  var var1 = 'var1';
}

one();

//output
closure var1 - var1
Enter fullscreen mode Exit fullscreen mode

Shared with ❤️ from Codever.   👉   use the copy to mine functionality to add it to your personal snippets collection.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more