
Javascript Loops: for, while & do-while
8 March, 2023
4
4
0
Contributors
Introduction
Loops are a fundamental concept in Javascript that allow you to execute a block of code repeatedly. There are several types of loops in Javascript, but the most commonly used are the for
loop and the while
loop.
for();
The for
loop is used to execute a block of code a specific number of times. It's usually used when you know the number of times you want the code to be executed, Here's a basic syntax of a for
loop
for (initialisation; condition; increment/decrement) {
// code to be executed
}
The initialisation
statement is used to initialise the loop counter variable. The condition
statement is used to specify the condition that must be true for the loop to continue. The increment/decrement
statement is used to modify the loop counter variable after each iteration of the loop.
Here's an example of a for loop that prints the numbers 1 to 5:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
In this example, we've initialised a variable i
to 1. The loop will continue as long as i
is less than or equal to 5. After each iteration of the loop, i
is incremented by 1. This loop will print the numbers 1 to 5 to the console by returning each iteration's value for i
.
while();
The while
loop is used to execute a block of code while a certain condition is true. It's usually used when you don't know the number of times you want the code to be executed, but you do know the condition that must be true for the loop to continue. Here's the basic syntax of a while
loop:
while (condition) {
// code to be executed
}
The loop will continue executing as long as the condition is true. Here's an example of a while
loop that prints the numbers 1 to 5:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
In this example, we've initialised a variable i
to 1. The loop will continue executing as long as i
is less than or equal to 5. After each iteration, i
is incremented by 1. This loop will print the numbers 1 to 5 to the console.
do{}while();
The do-while
loop is similar to the while
loop, but the block of code is executed at least once before the condition is checked. Here's the basic syntax of a do-while
loop
do {
// code to be executed
} while (condition);
The loop will execute the block of code at least once, and will continue executing as long as the condition is true. Here's an example of a do-while
loop that prints the numbers 1 to 5:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
In this example, we've initialised a variable i
to 1. The loop will execute the block of code at least once, and will continue executing as long as i
is less than or equal to 5. As with the previous examples, after each iteration of the loop, i
is incremented by 1. This loop will print the numbers 1 to 5 to the console.
Loop conditions
It's important to be careful when using loops to avoid infinite loops, which occur when the loop condition is always true, causing the loop to execute indefinitely. You can avoid infinite loops by ensuring that the loop condition is eventually false, or by using a break statement to exit the loop prematurely.
continue;
The continue
statement skips over specific iterations of a loop, for instance:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
In this example, we have a for
loop that iterates from 1 to 10. However, we only want to print out the odd numbers in this range. We use an if
statement to check if the current value of i
is even (i.e., if it is divisible by 2 with no remainder). If it is even, we use the continue
statement to skip over the rest of the loop code and move on to the next iteration.
If i
is odd, the console.log()
statement is executed and the value of i
is printed to the console. This loop will output the numbers 1, 3, 5, 7, and 9 to the console.
Using the continue
statement in this way allows us to skip over certain iterations of a loop based on a specific condition, without having to write separate code to handle those cases.
return;
If you want to exit a loop and/or a function, you could use the return
statement:
function findIndex(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
const numbers = [5, 10, 15, 20];
const index = findIndex(numbers, 15);
console.log(index); // Output: 2
In this example, we have a function called findIndex
that takes an array arr
and a target value target
. The function uses a for
loop to iterate over each element in the array, checking if the current element is equal to the target
value. If it is, the function uses the return
statement to exit the loop and return the index of the element.
If the loop completes without finding a matching element, the function returns -1. We then call the findIndex
function with an array of numbers and the target
value of 15. The function finds the value 15 at index 2 in the array and returns this index, which is then logged to the console.
Using the return
statement in this way allows us to exit a loop and a function at the same time, based on a specific condition. This is a powerful technique for writing more efficient and readable code, especially in cases where we need to search for a specific value in an array or perform some other operation on a set of data.
Overall, understanding how to use loops effectively is essential for any Javascript developer, as loops are a fundamental building block for many algorithms and programs.
Conclusion
In summary, loops are a powerful tool in Javascript that allow you to execute a block of code repeatedly. The for
loop is used when you know the number of times you want the code to be executed, while the while
loop and do-while
loop are used when you don't know the number of times you want the code to be executed.