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.
👉 Use the Copy to mine
functionality to copy this snippet to your own personal collection and easy manage
your code snippets.
Codever is open source on Github ⭐🙏