JavaScript | Looping Examples/Programs

Looping Example/Program in JavaScript: Here, we have some of the looping example/programs to understand the looping in JavaScript.
Submitted by Pankaj Singh, on October 18, 2018

1) Print numbers from 1 to 10 using 'while' loop

```<!DOCTYPE html>
<html lang="en">
<script>
var a=1;
while(a<=10){
document.write(a+"<br />");
a++;
}
</script>
<body>

</body>
</html>
```

Output

```    1
2
3
4
5
6
7
8
9
10
```

2) Print numbers from 1 to 15 using 'do while' loop

```<!DOCTYPE html>
<html lang="en">
<script>
var a=1;
do{
document.write(a+"<br />");
a++;
}while(a<=15);
</script>
<body>

</body>
</html>
```

Output

```    1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
```

3) Print numbers from 1 to 20 using 'for' loop

```<!DOCTYPE html>
<html lang="en">
<script>
var a;
for(a=1;a<=20;a++){
document.write(a+"<br />");
}
</script>
<body>

</body>
</html>
```

Output

```    1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
```

4) Print list (set of strings) using 'forEach' loop

```<!DOCTYPE html>
<html lang="en">
<script>
var fruits=["apple","mango","banana","guava"];
fruits.forEach(function(item){
document.write(item+"<br />");
});
</script>
<body>

</body>
</html>
```

Output

```    apple
mango
banana
guava
```