What are loops in javascript | Types of loops in javascript

Loops in JavaScript are programming constructs that allow you to repeat a set of instructions or a block of code multiple times. 

Javascript image

Loops are useful for repetitive tasks and processing data efficiently. Think of loops as a way to tell your computer to do something repeatedly until a certain condition is met.

Here are some of most commonly used loops in javascript programming.

1. For loop:

This loop is used when you know in advance how many times you want to execute a block of code. Consider following syntax/example for better understanding which prints 1 to 4 numbers in console using for loop.

In following example, As soon as value of variable "i" is 5 the loop condition becomes false and loop breaks.
for (let i = 0; i < 5; i++) {
  console.log(i);
}

Output :

0
1
2
3
4

2. While loop :

This is used when you want to execute a block of code as long as a condition is true. Consider following syntax/example for better understanding which prints 1 to 3 number in console using while loop.

In following example, As soon as count variable value becomes 4 the while condition will became false and loop breaks.
let count = 0;
while (count < 4) {
    console.log(count);
    count++;
}

Output :

0
1
2
3

3. Do-While Loop :

This is similar to a while loop but ensures that the block of code is executed at least once, even if the condition is initially false.

Consider following syntax/example for better understanding. where 1 to 5 numbers are printed in console in reverse direction using do-while loop.

When num value become 1 the code inside do block is executed and after printing number 1 into console the loop breaks.
let num = 5;
do {
    console.log(num);
    num--;
while (num > 0);

Output :

5
4
3
2
1

4. For-In Loop :

This loop is used to iterate over the properties of an object. Consider following syntax/example for better understanding.

As per following example person object have 3 properties name, age and gender and the for-in loop will print each property key and value in console one by one.
const person = {
    name: "John",
    age: 25,
    gender: "Male"
};

for (let key in person) {
    console.log(key + ": " + person[key]);
}

Output :

name: John
age: 25
gender: Male

5. For-Of Loop :

This is used to iterate over the values of iterable objects like arrays, strings, or maps. Consider following syntax/example for better understanding.

As per following example the colors array have 3 values and the for-of loop will print each array element in console one by one.
const colors = ["red", "green", "blue"];

for (let color of colors) {
    console.log(color);
}

Output :

red
green
blue
Thanks for reading this article, if you found this article useful then share it with your friends and share your thoughts in comment section.

Want to learn more about javascript? checkout these amazing  Javascript Tutorials .

Comments