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 (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.
for(let i=0; i<=5; i++){
console.log("The value is " + i);
}
This will give the following result -
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.
while (condition) {
statement
}
let i = 0;
while (i < 3) {
let multiply = i * 2;
i++;
console.log(multiply);
// expected output: 0, 2, 4
}
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.
do {
statement;
} while (condition);
let n = 5
do {
let square = n * n;
n--;
console.log(square);
// expected output: 25, 16, 9, 4, 1
} while (n>0);
This loop iterates over object properties.
for(variable in object){
statement
}
variable
A different property name is assigned to variable on each iteration.
object
Object whose properties are iterated over.
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
}
This loop iterates over Array, array-like objects.
for(variable of iterable){
statement
}
variable
On each iteration a value of different property is assigned to variable.
iterable
Object whose properties are iterated.
let fruits = ["Apple", "Banana", "Grapes", "Guva"];
for (let names of fruits) {
console.log(names);
// expected output: Apple, Banana, Grapes, Guva
}