Java Script Looping Statements

In this blog I will try to explain each and every looping statement in Java Script with an example and how it can used with arrays in general.

Below is the list of loops used in Java Script.

1. for loop :

syntax : for (;;) {
//
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Example

for (i = 0; i < 5; i++) {
text += “The number is “ + i + “<br>”;
}
o/p:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

2. while loop :

syntax :while () {

}

The while loop loops through a block of code as long as a specified condition is true.

Example

while (i < 10) {
text += “The number is “ + i;
i++;
}
o/p:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

3. do while

syntax :do {
}
while ();

This loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Example

var text = “”;
var i = 0;
do {
text += “The number is “ + i;
i++;
}
while (i < 5);
o/p:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

4. forEach

New in ECMAScript 5.

syntax : .forEach()

The forEach() method calls a function once for each element in an array, in order.

Note: the function is not executed for array elements without values.

Example

List each item in the array:var fruits = [“apple”, “orange”, “cherry”];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById(“demo”).innerHTML += index + “:” + item + “<br>”;
}
o/p:
0:apple
1:orange
2:cherry

5. for of

syntax : for (const element of array) {
// console.log(element);
}

The JavaScript for/of statement loops through the values of an iterable objects

for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.

Example

var cars = ['BMW', 'Volvo', 'Mini'];
var x;

for (x of cars) {
document.write(x + "<br >");
}
o/p:
BMW
Volvo
Mini

6. for in

syntax : in 

The JavaScript for/in statement loops through the properties of an object:

Example

var person = {fname:”John”, lname:”Doe”, age:25};var text = “”;
var x;
for (x in person) {
text += person[x];
}
o/p:
John Doe 25

Programming Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store