Try guessing what is the output of the following snippet:
function one() {
function two() {
console.log(`closure var1 - ${var1}`);
}
three();
var var1 = 'var1';
}
one();
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
Shared with ❤️ from Codever. 👉 use the copy to mine functionality to add it to your personal snippets collection.
Top comments (0)