Why JavaScript loops behave differently with let and var

💡 Have you ever wondered why these two JavaScript loops behave differently? for (let i = 0; i < 10; i++) {  setTimeout(() => console.log(i), 0); } for (var i = 0; i < 10; i++) {  setTimeout(() => console.log(i), 0); } It’s because of the default behavior of how let and var work in JavaScript. If you’re familiar with JavaScript, you may know that let is block-scoped, while var is function/global-scoped. In the case of let, since it’s block-scoped, it creates a new variable i and assigns a value to it during each iteration. So, each i points to a different memory location — kind of like a house with multiple rooms, and each room contains its own variable called i. That’s why it logs 0 to 9 after the wait is over. But in the case of var, since it’s function/global-scoped, the variable is created only once and points to the same memory location. So it logs 10 ten times. It’s similar to writing: var i; for (i = 0; i < 10; i++) {  setTimeout(() => console.log(i), 0); } #Javascript #Frontend

To view or add a comment, sign in

Explore content categories