Types of Javascript Loops
For Loop Syntax
for
loop is used to repeat block of code and perform different task with same code while condition is true. For loop has three section-
- initialize - initializing the variables and it executes only once when loop start.
- condition or expression - checking the condition in every interation.
- update the condition
for(initialize; condition; update)
{
// repeating code
}
Example
here is the example of for loop to print the number 0 to 10.
//printing number using for loop upto 10 (start with 0 and end with 10)
for (let i = 0; i < 11; i++) {
document.write(i+" ");
}
While Loop
while
loop is used to execute the block of code while condition is true. In the while
parenthesis we have to specify the condition. Loop must be terminate after performing the task. Infinite loop may freeze your pc.
while (condition) {
// code
}
Example Of While Loop
In this example, i
variable is initialized with 1 and condition is i 'less than or equal to 50' and increment the variable i to update the value to print the number upto 50.
let i = 1; //initialize a variable
while (i <= 50) // condition
{
document.write(" ", i);
i++; // increment
}
Do While Loop
do while
loop is same as while loop but it has conditional statement at the end. First it will execute the code then check the condition. syntax is here
do {
// code
} while (condition); //condition
Example:
print the value of variable 'a' as long as it is not equal to 10.
let a = 1;
do {
document.writeln(a);
a= a+1; //increment
} while (a !=10); //condition
For In Loop
for in
loop is specially used for iterable object. It returns a key in every interation . Using their key we can access value. for in
loop used to print the value of a object as long as it's key is available is object. syntax is here
for (let key in object) {
let element = object[key];
// code
}
Example:
In this example accessing the key and value of an object using for in
loop.
// course is an object which has key and value
const course = {100:"javascript", 200:"php", 300:"python", 400:"c++" ,500:"java"};
for (let id in course)
{ // in every iteration id contain the key of object course such as 100, 200, 300, 400, 500
document.writeln(course[id]);
}
Accessing Array Element Using For In Loop
let array = [10, 20, 30, 40, 50];
for (let index in array) {
document.write(array[index]);
}
For Of Loop
for of
loop is used in iterable data structure such as array, string, map and more. It return the value of iterable object.
let array = [10, 20, 30, 40, 50];
// for of loop return value of array in every iteration
for (let value of array)
{
document.write(" ",value);
}
Example Of For Of Loop
In this example accessing value of an iterable object using for of
loop.
// language is an object which has key and value
const language = ["javascript", "php", "python", "c++", "java"];
for (let value of language) { // in every iteration value contain the value of object
document.write(" ", value);
}