An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
7 different ways of Looping in JavaScript with example.
In this blog, you will learn about the 7 different ways of Looping in JavaScript with the help of examples.
For example, if you want to show a message 100 times, then you can use a loop. It's just a simple example; you can achieve much more with loops.
List of Loops in JavaScript
There are 7 kinds of loops you will find in JavaScript. I've listed them in an order that will help you to get a clear view of their working process and usage. This article will also help you to differentiate between all these 7 loops like where, when, or how you should use them. So lets start.
while
do-while
for
forEach()
map()
forin
forof
1. while loop
while loop
is one of the most basic kinds of loops available in JS. If JavaScript is not the only programming language you know, you must have heard about this one already.
The while statement generates a loop that gets executed over a particular block of the statement (code) as long as the condition is true. Every time before executing the block of code the condition gets checked.
while loop Syntax
while (condition) {
Block of code
}
while loop Example
let i=5;while (i<10){ console.log("I is less than 10"); i++;}
Output
I is less than 10I is less than 10I is less than 10I is less than 10I is less than 10
In the above example, the condition is getting checked if the value of i is less than 10 or not. If the condition is true, the block of code gets executed and before iterating next time the value of i is getting increases by 1 as weve added a statement i++
.
2. do-while Loop
do-while
loop is slightly different from while as it includes one extra feature. In case of do-while
loop, the block of code gets executed at least once and if further the condition satisfies the code block will be executed accordingly.
do-while Loop Syntax
do {
Block of code
}
while (condition);
Example
let i=5;do{ console.log("The value of i is " + i); i++;}while(i>5 && i<10);
Output
The value of i is 5The value of i is 6The value of i is 7The value of i is 8The value of i is 9
As you can see the condition is- *the value of i
is greater than 7 but less than 10; but in output the value of i=7
has been printed. Because this looping technique first do
execute the code irrespective of the condition and then compares the condition from 2nd round of execution. For all the true condition from the 2nd looping round the code block will be executed.
Continue Writing......
Original Link: https://dev.to/arman_aru/7-different-ways-of-looping-in-javascript-with-example-1g50
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To