Loops are commonly used to execute a block of code repeatedly, with different values each time, until a specific condition is met. They are widely employed for tasks such as iterating through values in an array, calculating sums, invoking functions repeatedly, and more.
In this article, we will explore how to utilize loops in JavaScript to iterate through array elements. JavaScript offers several types of loops:
forloop executes a code block for a specified number of iterations.forEach()executes a function for each element in an array or NodeList.for...initerates over the properties of an object.for...ofiterates over the values of an iterable object.whilerepeats a code block while a given condition is true.do...whileexecutes a code block at least once, then repeats it as long as a condition remains true.
Iterating through an array using a for loop
The for loop is commonly used to iterate over arrays and NodeLists in JavaScript. It follows this syntax:
for (init; condition; expr) {
// code block to be executed
}
In the above syntax, the for loop consists of three statements:
- The
initstatement executes once before the code block begins. It defines the starting point for the loop, allowing you to loop through the entire array or start at a specific position. - The
conditiondefines the condition that must be true for the loop to continue executing the code block. It is checked after each iteration, and if it evaluates totrue, the loop continues. If it evaluates tofalse, the loop terminates. - The
exprstatement is executed after each iteration of the code block. It can be used to increment or decrement the counter variable.
Consider the following example:
const birds = ['🐦', '🦅', '🦆', '🦉']
// Loop through all birds
for (let i = 0; i < birds.length; i++) {
console.log(birds[i]) // Current value
console.log(i) // Current index
}
In this example, we use the init statement to initialize a variable i as a counter. The condition statement ensures that the counter remains smaller than the total number of elements in the array. Finally, the expr statement increments the counter by 1 after each iteration.
Inside the loop, we can use the counter variable i to access the current item from the array.
Iterating through an array using a forEach() loop
The Array.forEach() method, introduced in ES6, allows executing a specified function for each element of an array in ascending order.
Here's an example demonstrating the usage of forEach() to iterate through array elements in JavaScript:
const birds = ['🐦', '🦅', '🦆', '🦉']
birds.forEach((bird, index) => {
console.log(`${index} -> ${bird}`)
})
// Output:
// 0 -> 🐦
// 1 -> 🦅
// 2 -> 🦆
// 3 -> 🦉
The index parameter is optional and can be omitted if not required:
birds.forEach(bird => console.log(bird))
Unfortunately, there is no direct way to terminate the execution of a forEach() loop.
Iterating through an array using a for...in loop
The for...in statement iterates through the properties of an object.
Consider the following example:
const person = {
name: 'John Doe',
email: 'john.doe@example.com',
age: 25
}
for (const prop in person) {
console.log(prop) // Property name
console.log(person[prop]) // Property value
}
While for...in is primarily designed for object properties, it can also be used with an array (although not recommended):
const digits = [2, 3, 5]
for (const index in digits) {
console.log(digits[index])
}
// Output:
// 2
// 3
// 5
Iterating through an array using a for...of loop
The for...of statement, introduced in ES6, allows iterating over the values of iterable objects such as arrays, strings, maps, sets, and more.
Consider the following example:
const birds = ['🐦', '🦅', '🦉']
// Iterate over all values
for (const bird of birds) {
console.log(`Hey ${bird}`)
}
// Output:
// Hey 🐦
// Hey 🦅
// Hey 🦉
The key distinction between for...in and for...of loops is that the former iterates over property names, while the latter iterates over property values.
Iterating through an array using a while loop
The while loop repeatedly executes a code block as long as a specified condition remains true. Here's an example:
const cars = ['BMW', 'Porsche', 'Audi', 'Tesla']
let i = 0
while (i < cars.length) {
console.log(i) // Index
console.log(cars[i]) // Value
i++
}
Remember to increment the counter variable i within the loop. Otherwise, the loop will never terminate. To terminate a while loop, you can use the break statement:
while (i < cars.length) {
// Terminate if index equals 2
if (i === 2) {
break
}
// TODO: Perform desired actions here
}
To skip an iteration, use the continue statement:
while (i < cars.length) {
// Skip the second iteration
if (i === 2) {
continue
}
// TODO: Perform desired actions here
}
Iterating through an array using a do...while loop
The do...while loop is similar to the while loop, with the key difference being that the do...while loop executes the code block at least once before checking the condition. If the condition is true, it repeats the code block as long as the condition remains true.
Consider the following example of a do...while loop:
const cars = ['BMW', 'Porsche', 'Audi', 'Tesla']
let i = 0
do {
console.log(i) // Index
console.log(cars[i]) // Value
i++
} while (i < cars.length)
Similar to the while loop, you can utilize break and continue statements to terminate the loop or skip iterations.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.