Look at this code.
function func() {
let x = 0;
setTimeout(() => {
console.log(x);
}, 3000);
}
func();
My question is why we can access variable "x" inside of setTimeout function. I know sounds stupid but let me explain. As i know whenever function is envoked a new execution context is created and puts inside of a call-stack. This context is where our variable are stored. And when we are trying to access a variable inside a function that was declared somewhere else, js engine goes down the call-stack and tries to find this variable inside one of the "parent's" execution context. BUT, as we all know js in a single-threaded language, which means it executes all async operations only when callstack is empty. So this is where my confusion comes from. How we can access variable "x" inside of a setTimeout callback if
- Inside callback's execution context there is not such variable.
- Callstack is empty, so js engine cannot traverse it to find such variable
And one more question. When i change my code like this why is it printing 2.
function func() {
let x = 0;
setTimeout(() => {
console.log(x);
}, 3000);
x = 2;
}
func();