Java Script Looping Statements

Sumeet Panchal
3 min readMay 31, 2020

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

2. while loop

3. do loop

4. forEach (new in ECMAScript 5)

5. for of (advance looping)

6. for in (advance looping)

1. for loop :

syntax : for (statement 1; statement 2; statement 3) {
// code block to be executed
}

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 (condition) {
// code block to be executed
}

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 {
// code block to be executed
}
while (condition);

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 : array.forEach(function(currentValue, index, arr), thisValue)

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 :for (var in object) {
// code block to be executed
}

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

--

--