Loops
Loops are another of the most fundamental concepts in javascript programming. A very common scenario when programming is needing to execute the same line or lines of code numerous times. Rather than typing the same code out repeatedly, we can use a loop to execute the same code multiple times. There are 2 main types of loops, for and while loops. For loops will execute their code a specific amount of times, whereas while loops will execute their code until their specified condition is false.
Let’s take a look at a for loop first and break down its parts:
for (let i = 0; i < 10; i++) {
console.log(i)
}
The for loop has 3 parts: Initialization (let i = 1): Sets the starting point for the loop Condition (i < 10): Determines how many times the loop runs Increment (i++): Updates the counter after each loop
For loops can be particularly useful when looking at arrays. If we wanted to print out each variable in an array, we could do so as follows using a loop:
const fruits= ["apple", "banana", "orange"]
for(let i = 0; i < array.length; i++) {
console.log(fruits[i])
}
The second kind of loop is a while loop. While loops are similar to for loops except they only have a condition in their brackets, and the incrementation needs to be done within the code in the loop. It’s important to always include the incrementation step in the loop, as its easily possible to get stuck with a program repeating forever if you forgot it.
let count = 0
while (count < 10) {
console.log(count)
count++
}