Hoisting with closures example

Via hoisting, memory is allocated to the variable var1, but it is not initialised by the time the closure is executed

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

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

one();

//output
hoisting var1 - undefined

But if we use setTimeout(), by the time 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

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures


Shared with from Codever.land. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

Dynamically expand angular material panel when condition met

Dynamically expand angular material panel when condition met code snippet Continue reading

Copy to clipboard with angular material

Published on October 12, 2022