DEV Community

The web developer
The web developer

Posted on

What are loops in JavaScript and why use them?

Loops in JavaScript are a very important topic and it is very important for you to learn what are loops and why to use them.

Suppose, we have a single line of code or a block of code and we want to print it up to n-times(n = 1,2,3,4,5,6,... or 100) as shown in e.g # 1

Example # 1:

Source code:

console.log("Hello world! ");
console.log("Hello world! ");
console.log("Hello world! ");
console.log("Hello world! ");
Enter fullscreen mode Exit fullscreen mode

Output :

 Hello world! Hello world! Hello world! Hello world!
Enter fullscreen mode Exit fullscreen mode

In the above example we have a single line of code that we want to print four times so we wrote 'console.log("Hello world! ");' for four times.

In the above example, we just wanted to write the one line of code only four times so but what if we want to write the same line of code up to 20-times or 30-times, then it would never be a good strategy to write the one line of code up to 20 or 30-times.

So, here comes the concept of the loop in JavaScript. JavaScript loop provides us the facility and makes our code much shorter.

We have multiple loops in JavaScript.

i.e

1 for loop
2 while loop
3 do while loop
4 for each loop

Below is an example that demonstrates the concept, using for loop

Example # 2 :

Source code:

for(var i = 0; i < 4; i++){
console.log("Hello world! ");
}

Output:

Hello world! Hello world! Hello world! Hello world!

Example 1 VS Example 2 :
In example one we wrote one line of code four times and at the same time, we wrote the same line of code for one time which will be executed four times.
So, that was the practical demonstration of the loop.

Conclusion:

JavaScript loops allow us to execute the same code a number of times (as you can see in Example # 2) instead of writing the same code individually (as you can see in Example # 1). That is why loops are very useful in JavaScript

Top comments (2)

Collapse
 
efpage profile image
Eckehard

You should mention map() as an option to enumerate arrays in JS:

["hello 1","hello 2","hello 3"].map(name => console.log(name))

Collapse
 
hamza786504 profile image
The web developer

Yes, you can use map method as we if you want to print the array