DEV Community

Hina M.M
Hina M.M

Posted on

A Beginner's Guide to For, While, and Nested Loops in JavaScript-

If you're learning to code in JavaScript, you'll quickly find that loops are a fundamental part of the language. Loops allow you to repeat a block of code multiple times, making your code more efficient and flexible. There are three types of loops in JavaScript: for, while, and nested loops. In this post, we'll explore each type of loop in detail, and provide examples to help you understand how they work.

For Loops

A for loop is used to iterate over a range of values, such as an array or a string. The basic syntax for a for loop looks like this:

for (initialization; condition; increment/decrement) {

Code to be executed

}

Let's break down each part of the " for loop "syntax:

Initialization: This is where you set the initial value of the loop variable. For example, if you want to loop through an array, you might set the loop variable to 0.

Condition: This is the condition that is checked before each iteration of the loop. If the condition is true, the loop continues; if it's false, the loop ends.

Increment/decrement: This is how the loop variable is changed on each iteration of the loop. You can either increment the loop variable (i++) or decrement it (i--).

Example 1: Printing numbers from 1 to 5

for (let i = 1; i <= 5; i++) {

console.log(i);

}

This will output:

1

2

3

4

5

While Loops:

A while loop is used when you don't know how many times you need to iterate, but you know the condition that must be met for the loop to continue. The basic syntax for a while loop looks like this:

while (condition) {

Code to be executed

}

The condition is checked before each iteration of the loop. If it's true, the loop continues; if it's false, the loop ends. Here's an example of a while loop that generates random numbers until a number greater than 0.5 is generated:

let randomNum = Math.random();

while (randomNum <= 0.5) {

console.log(randomNum); randomNum = Math.random();

}

Nested Loops:

A nested loop is a loop inside another loop. Here's an example of how to use nested loops to print out all the possible combinations of fruits and colors:

let fruits = ["apple", "banana", "orange"]; let colors = ["red", "yellow", "orange"];

for (let i = 0; i < fruits.length; i++) {

for (let j = 0; j < colors.length; j++) {

console.log(fruits[i] + " " + colors[j]);

}

}

This will output :

apple red

apple yellow

apple orange

banana red

banana yellow

banana orange

orange red

orange yellow

orange orange

Conclusion

Loops are an essential part of JavaScript programming. For loops are used to iterate over a range of values, while loops are used when you don't know how many times you need to iterate, and nested loops are used when you need to perform multiple iterations over two or more arrays. By understanding the basics of loops.

Top comments (0)