DEV Community

Adrian Matei for Codever

Posted on • Updated on • Originally published at codever.land

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.

Discussion (0)