Loops in JavaScript
Loops are used when we want to repeat an action or run some code multiple times
- for Loop
- for…in Loop
- foreach Loop
- while Loop
- do…while Loop
for Loop
The for loop is used when we want to execute the set of statements for a certain number of times.
Example :
for(var j=1; j<=7; j++)
{
console.log(j);
}
//check log in browser for output
for…in Loop
It is a special type of loop, used when we want to iterates over the properties of an object or the elements of an array.
Example :
var person = {name: "Shree", language: "JavaScript", age: 28};
for(var p in person)
{
console.log( p + " = " + person[p]);
}
foreach Loop
With the help of forEach loop, we can execute a function on each item within an array.
Example :
const evenno = [2,4,6,8,10];
evenno.forEach(showen);
function showen(item, index)
{
console.log(item);
}
while Loop
A while loop is used when we do not know how many times a certain block of code should execute.
Example :
let x = 1, y = 6;
while (x <= y)
{
console.log(x);
x += 1;
}
do..While Loop
In this loop, the body inside the do statement is executed first,then the condition is evaluated.
Example :
let a = 1;
let b =3;
do {
console.log(a);
a++;
} while(a <= b);