Loops and Iteration in JavaScript
Loops allow you to perform a given task repeatedly. There are many kinds of loops which behave differently.
For Loop
The for loop is effective when you know how many times you want to execute a block of code. For loops take 3 expressions:
for (Initialisation; condition; update) {
//statement.
}
Initialisation: This is the first expression. It initialises a variable, often used as a loop counter, to track the iterations.
Condition: The statement will only execute if the condition is evaluated to be true, the loop does not run when false.
Update: Executed after each iteration, commonly used to update/increment the loop counter variable.
Lets take a look at an example:
for (let i = 0; i < 5; i++) {
console.log(i);
} //outputs 0, 1, 2, 3, 4
The variable loop counter is i, ‘i’ is commonly used as a name for loop counters. The variable is initialised with a value of 0.
The Condition states that if i is less than 5, the loop should continue to iterate.
For the update expression, i will be increased by 1 after each iteration. i++ increases the variable by 1 each iteration, you could use i = i + 1 (does the same thing).
i will be increased by 1 with each iteration, until it has the value of 5 – then the Condition would be false and the loop would stop because i < 5 would no longer be true.
The loop is exclusive of the value where the Condition becomes false
(e.g., i < 5
means 5
is not included).
While Loop
while (condition) {
//statement.
}
While loops will iterate as long as your specified condition evaluates to true. Here is a example:
let i = 0;
while (i !== 6) {
console.log("balls")
i++;
} //Output: balls, balls, balls, balls, balls, balls
Our loop counter i is being initialised with a value of 0. Unless you want to reset the loop counter each iteration, you should initialise the counter outside of the loop.
The condition is (condition !== 6), meaning the loop will execute the statement as long as i is not equal to 6. The statement tells JavaScript to console.log “balls” and increase i by 1 with each iteration.
Before executing your code make sure your condition has a end point, otherwise the while loop could result in a infinite loop. Here is an example of an infinite loop:
let i = 0;
while (i !== 7) {
console.log("balls") //removed i++
}
//Output: balls, balls, balls, balls, balls, balls, balls, balls...
The line that was incrementing i has been removed, so the value of i will remain 0 after every iteration. But the condition is still checking for i to not equal 7, causing a infinite loop.
Do…While Loop
The do while loop is similar to the while loop, but the do..while loop will execute at least once before stopping.
let count = 0;
do {
console.log("green")
count++;
} while (count !== 0);
//Output: "green"
- We initialised count as the loop counter. On each iteration, “green” will be logged to the console and count will be increased by 1.
It is true that count is initially 0, but the loop runs before the condition is checked. This causes do…while loops to execute the code at least once before stopping, they execute and then check for condition to determine whether to run again.
One of the most common applications of a do…while loop is in user input validation. When you need to prompt users for input until they provide a valid response, a do…while loop can ensure that the prompt appears at least once.
et userInput;
do {
userInput = prompt("Enter a number greater than 10:");
} while (userInput <= 10);
// Ensures the prompt appears at least once, even if the input is initially invalid.
For…in Loop
For…in loops iterate through the properties (keys) of an object, or the indices of an array. It retrieves the keys/property names. To understand, lets first quickly review how objects work.
Objects are made of key-value pairs, objects have keys which are assigned a value. Here is an example of an object:
const myCar = {
color: "blue",
car-brand: "honda",
milage: 150000,
}
For the for…in loop, your start with ‘for’, then initialise a variable, followed by ‘in’, then the object you want to access. Then the code you want to execute in curly brackets {}.
The variable is variable name that you declare for this loop, it will hold the keys of the object (property name) during the loop. In the last expression, you enter the object you want to iterate through.
for (variable in object) {
//code to execute.
}
Where
- Variable is the name of the variable you declare for the loop. It will hold the keys of the object during each iteration.
- Object is the object you want to want to iterate through.
Lets create a loop using our previous example object.
const myCar = {
color: "blue",
brand: "toyota",
mileage: 150000
}
for (let carFeats in myCar = {
console.log(carFeats);
}. //Output: colour, brand, mileage
We used let to initialise ‘carFeats’ to hold the keys in the object ‘myCar’. So when we used the loop to log carFeats, it retrieved the keys – “colour”, “brand”, and “milage”.
To get the values of the keys, you need to reference the original object post with bracket notation.
for (let carFeats in myCar) {
console.log(myCar[carFeats]); // variable[object]
}.
//Output: blue, toyota, 150000
For…of Loop
Here is the basic syntax for a for…of loop:
for (variable of iterable) {
//statement
}
- The variable holds the values of your iterable being looped over.
- The iterable can be any collection that implements the iterable protocol, like arrays, strings, maps, sets, etc.
Here is an example of a for…of loop:
const numbers = [2, 4, 7, 13, 14]
for (let number of numbers) {
console.log(number) //directly accessing the value sof hte array
}
//Output: 2, 4, 7, 13, 14
This loop will access the values of the ‘numbers’ array and store them in a variable named ‘number’. The for…of loop retrieves values of the loop, you don’t need to reference the original array in the statement to retrieve the values.
forEach Method
The forEach loop isn’t considered a traditional loop in JavaScript, but it works similarly and can be useful because it allows you to iterate over array items without managing indices. It also provides for flexibility for callback functions.
Here is the basic syntax:
yourArray.forEach((element, index, array) => {
// statements
});
element
: The current element being processed in the- array.
index
(optional): The index of the current - element.
array
(optional): The original arrayforEach
is being iterated over.
The forEach method takes a callback function, which is executed for each element in the array.
Here is an example:
const numbers = [1, 2, 5, 10, 12, 15];
numbers.forEach((number) => {
console.log(number * 2);
});
// Output: 2, 4, 10, 20, 24, 30
- We created an array called
numbers
. - The
forEach
method is used on the array. - The callback function is an anonymous arrow function that takes a parameter, ‘number’, which represents the current element.
- Inside the function,
number * 2
is logged to the console for each element in the array.
Note: The forEach
method does not return a new array. Its purpose is to execute a function for every array element, often for side effects like logging or modifying variables.
You don’t have to pass a anonymous arrow function as the callback function, you can pass a named function.
function logDouble(number) {
console.log(number * 2);
}
numbers.forEach(logDouble);
// Output: 2, 4, 10, 20, 24, 30
Break Statement
The break
statement immediately exits out of the loop in which it is placed, but the program continues executing.
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i); // Outputs: 0, 1, 2, 3, 4
}
- The for loop starts from i = 0 and increments up to 9.
- When i is equal to 5, the break statement is executed, causing the loop to exit immediately.
- Therefore, the loop outputs:
0, 1, 2, 3, 4
.
Labeled Statements
Labeled statements allow you to assign a loop or block of code. This is useful when you are working with nested loops as it makes it easier to target specific ones.
labelName: for (let i = 0; i < 5; i++) {
if (condition) break labelName;
}
- LabelName: The name being assigned to the loop.
- Break LabelName: allows you to break out of the labeled loop.
Here is an example:
outerLoop: for(let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break outerLoop
console.log(`i=${i} j=${j}`);
}
}
//Output: i = 1, j = 2
- We created a loop, labeled ‘outerLoop’.
- The inner for loop is nested inside ‘outerloop’.
- Break Condition: The
if (j === 1)
condition checks ifj
equals1
. When this happens, it breaks out of theouterLoop
, not just the inner loop. - The loop will print the values of
i
andj
for the first iteration of the outer loop (i = 0
) and the first iteration of the inner loop (j = 0
). However, whenj
becomes1
, thebreak outerLoop
statement will exit both loops immediately.
Continue Statement
The continue statement is used to skip the current iteration and move on the next iteration.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue;
console.log(i);
}
//Ouput: 1, 3, 5, 7, 9
- In our for loop, i runs from 0-9.
- The if statement checks if i is even using (i % 2 === 0).
- If
i
is even, thecontinue
statement skips theconsole.log(i)
statement and moves to the next iteration. - The result is that only odd numbers (
1, 3, 5, 7, 9
) are logged to the console.
The condition i % 2 === 0
checks whether i
is even. The modulo operation returns the remainder when i
is divided by 2. If the result is 0, the number is even.
When continue
is executed, the current iteration of the loop is skipped, and the next iteration begins immediately, without executing any further statements in that iteration.
Thank you for reading my article. If you found it helpful, checkout my other articles. If you want an effective way to learn JavaScript, check out freeCodeCamp, they provide courses and free certifications.
