LOOPING STATEMENTS

Loops

If you want to run the same code over and over again, each time with a different value.

JavaScript supports different kinds of loops :

  • for - loops through a block of code a number of times
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true
  • for/in - loops through the properties of an object
  • for/of - loops through the values of an iterable object

for Loop

Syntax

for (initialization; condition; increment/decrement){
statement
}

Initialization

It is executed only one time before the execution of the code block.

Condition

If the condition is true then code block will execute else loop will terminate.

Increment/Decrement

It will execute every time after the code block has been executed.

Example :

for(let i=0; i<=5; i++){
console.log("The value is " + i);
}

This will give the following result -

for Loop

while Loop

While loop executes a statement as long as the specified condition is true. The while loop works same as for loop which is used only when we already knew the number of iterations. Where as the ‘while’ loop is used only when the number of iteration are not exactly known.

Here, initialization will be done above the while loop and iteration will be written anywhere in the loop.

Syntax

while (condition) {
statement
}

Example :

let i = 0;
while (i < 3) {
let multiply = i * 2;
i++;
console.log(multiply);
// expected output: 0, 2, 4
}

do while Loop

This do while loop also executes block of code until the specified condition is true. But the difference in do while and while loop is that the condition will be checked after the first execution.

In this do while loop, block of code will be executed at least once even the condition is false.

Syntax

do {
statement;
} while (condition);

Example :

let n = 5
do {
let square = n * n;
n--;
console.log(square);
// expected output: 25, 16, 9, 4, 1
} while (n>0);

for in Loop

This loop iterates over object properties.

Syntax

for(variable in object){
statement
}

variableA different property name is assigned to variable on each iteration.

objectObject whose properties are iterated over.

Example :

let emp = {
fname: "John",
lname: "Carter",
age: 55,
designation: "UX designer"
}
let person;
for(person in emp){
console.log(person);
// expected output: fname, lname, age, designation
console.log(emp[person]);
// expected output: John, Carter, 55, UX designer
}

for of loop

This loop iterates over Array, array-like objects.

Syntax

for(variable of iterable){
statement
}

variableOn each iteration a value of different property is assigned to variable.

iterableObject whose properties are iterated.

Example :

let fruits = ["Apple", "Banana", "Grapes", "Guva"];
for (let names of fruits) {
console.log(names);
// expected output: Apple, Banana, Grapes, Guva
}