JavaScript Loop Variable Scope Issue with `var`

In the "Wrong Syntax" example, the mistake lies in using the `var` keyword to declare the loop variable `i`. **The Issue:** `var` is function-scoped (or globally scoped), not block-scoped. Because of this, only one instance of the variable `i` is created for the entire loop, and its value is updated with each iteration. By the time the `setTimeout` callbacks execute (after 1000ms), the loop has finished, and `i` holds its final value of 5. Therefore, it logs "5" five times. **The Fix:** Using the `let` keyword, as shown in the "Correct Syntax" example, resolves this. `let` is block-scoped, which means a *new* variable `i` is created for each individual iteration of the loop, effectively "binding" the current value of `i` to that specific callback function. #JavaScript #CodingMistakes #Scope #WebDevelopment #ProgrammingTips

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories