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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs