JavaScript Fundamentals -- Looping in JavaScript

for Loops -- Why Use Them and Gotchas


There are two common "gotchas" when using for loops:

  1. using the const keyword for the local variable instead of let
  2. going out of bounds in an array

When you declare a variable using the const keyword, its value shouldn't be reassigned. But each time through the loop, we reassign the local variable's value to the next number (i.e. we add 1 to it). If you use the const keyword, you will get an error.

Side Note:

In StackBlitz, we don't see the error of reassigning a variable that was declared with the const variable. That's why there isn't an example here. Go back to the const vs let video to see examples.

Going out of bounds in an array means you are trying to access an element that doesn't exist. If you have an array that has 3 elements and you try to access the fourth, you will have gone out of bounds. Some programming languages stop execution there and throw an error. JavaScript doesn't do that; it just returns undefined for accessing that value. The issue comes when you pass that array value to another function that's expecting a value but gets undefined.

Any time you find yourself repeating the same exact code, or very very similar code, multiple times you should consider using a for loop. It allows you to write the code once and use it multiple times. It also makes it so that if you need to change the code you do so in one spot, and if you add something to an array for example it's automatically picked up.


I finished! On to the next chapter