function f() {
const color = "red";
setTimeout(() => console.log(color), 1000);
}
f();
In this code, setTimeout's callback (() => resolve(color), 1000
) is asynchronous and is put on the macro-task queue after 1 second. When the call-stack is empty, there is a chance for the callback to be pushed onto it.
I thought to myself, when this callback is executed on this 'refreshed' call-stack, it remembers everything it had access to when it first appeared on the call-stack during 'initial execution of script'. For instance, it can access color
. How is this possible? Is this the result of 'closures'? Does a deep-clone 'copy' of that function appear on the call-stack later and it can access all what it could access where that function was first defined? At this point I'm just guessing but I thought it a worthy question.