I've a few questions about closure. Sorry if it seems just another closure question, there are tons of posts and articles and I read so many, but I still have questions and couldn't find answers.
var message = 'Hello!';
document.getElementById('foo').onclick = function(){alert(message)};
message = 'Goodbye!';
Here "Goodbye" will be alerted and the explanation is: "A closure does not merely pass the value of a variable or even a reference to the variable. A closure captures the variable itself!"
a. Please, can anyone explain to me what "capturing variable itself" means and how is THAT responsible for the message to be "goodbye" and not "hello"?
b. the function or the alert is the closure?
c. Also, am I correct with the following: the onclick
is added to event table, that sends notice (when click occurred) to event queue, event loop checks call stack, its empty so the alert message is being added and executed. While all that is happening, JS engine already reached the line of code -> message = 'Goodbye!'; and this is why "Goodbye" is ultimately alerted?!
for (var i = 1; i < 5; i++) {
setTimeout(() => console.log(i), i*1000)
}
vs
for (let i = 1; i < 5; i++) {
setTimeout(() => console.log(i), i*1000)
}
for (var i = 1; i < 5; i++) {
(function(i){
setTimeout(() => console.log(i), i*1000)
})(i)
}
- I always read "by the time the first
setTimeout()
runs, i is already at 5, and we don’t have any way to reference it" - but what is the reason that when first setTimeout() runs, the loop has finished? Has that actually to do with the event queue etc?! - I also always read the problem is that variable i isn't referenced. I just don't understand how referencing variable i has anything to do with setTimeout running after loop already finished.
- when I use let, not var, I always read with let its block scoped, not function scoped so i doesn't become global.I understand. But could someone explain, what exactly happens - why/how is i not being global variable responsible for
setTimeout
NOT being called after for loop finished? I don't understand the connection. - Also, please can someone explain why with i*1000, i will not as I understand be always 5? Its because its outside of the closure?
Thank you so much and please if anything wasn't clear, let me know.