If you are not convinced of how extremely useful loops are by now, have a look at loops and arrays. Loops make life with arrays a lot more comfortable.
We can combine the length property and the condition part of the for loop (or while loop) to easily loop over arrays.
It would look like this in the case of a for loop:
let arr = [some array];for (initialize variable; variable < arr.length; statement) { // code to be executed }
Let's start with a simple example that is going to log every value of the array:
let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];for (let i = 0; i < names.length; i++) { console.log(names[i]); }
We use the length property to determine the maximum value of our index. The index starts counting at 0, but the length does not. The index is always one smaller than the length. Hence, we loop over the values of the array by increasing the index up to length - 1.
In the previous example, we aren't doing very interesting things yet; we are simply printing the values. But we could be changing the values of the array in a loop, for example, like this:
let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];for (let i = 0; i < names.length; i++) { names[i] = "hello " + names[i]; }
console.log(names);
We have concatenated "hello " with the beginnings of our names. The array is changed in the loop, and the array will have its content updated after the loop has executed.
The possibilities are endless here. When an array comes in somewhere in the application, data can be sent to the database per value. Data can be modified by value, or even filtered.
Let's look at an example where we filter the data:
let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];for (let i = 0; i < names.length; i++) { if (names[i].startsWith("M")) { delete names[i]; continue; } names[i] = "hello " + names[i]; }
console.log(names);
The startsWith() method checks whether the string starts with a certain character. In this case, it checks whether the name starts with the string "M".
Note: Don't worry if you don't know startsWith() yet, we will cover this function and many more in detail in a later chapter on Built-in JavaScript Methods.
You'll have to be careful here, though. If we were to remove the item using splice() instead of delete (which leaves an empty value undefined), we would accidentally skip the next value. This happens because that value gets the index of the recently deleted one, but i still increments and moves on to the next index!
What do you think this one does?
let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];for (let i = 0; i < names.length; i++) { names.push("..."); }
Warning: Your program gets stuck in an infinite loop here. Since a value gets added every iteration, the length of the array grows with every iteration, meaning i will never be bigger than or equal to names.length.
When looping over an array, why is the condition typically i < array.length instead of i <= array.length?