Different Loops in JavaScript
Let's check out different loops in JavaScript and how each one of them can be useful in different scenarios of programming.
Overview:
Loops are very useful in programming, whenever we want to perform any task and we want to repeat that task a particular number of times.
For instance, If we want to print orange 6 times :
console.log('orange'); //Output: orange
console.log('orange'); //Output: orange
console.log('orange'); //Output: orange
console.log('orange'); //Output: orange
console.log('orange'); //Output: orange
console.log('orange'); //Output: orange
In this example, we have written the same statement 6 times to print orange
6 times but if we want to do it 20 times, it might become longer and time-consuming.
If we do the same using loop:
for(let i=0;i < 5; i++){
console.log('orange');
}
//Output:
//orange
//orange
//orange
//orange
//orange
See how compact the code becomes using a loop we will discuss how loops work in the later part of the blog.
Types of loops in JavaScript:
We have different kinds of loops in JavaScript but all of them do the same thing which is to repeat a block of code or an action for some n number of times.
Different kinds of loops in JavaScript are:
for loop
for in loop
for of loop
while loop
do-while loop
for loop:
We use for loop to loop through a block of code for a given number of times. We provide for loop with some condition, for loop keeps on working until the condition remains true
.
Syntax:
for(initialization; condition; afterthought){
statement
}
We can divide for loop into three parts:
Initialization
Condition
afterthought
for(let i=0;i < 5; i++){
console.log('orange');
}
//Output:
//orange
//orange
//orange
//orange
//orange
Let's understand all three parts of for loop with the above example,
Initialization: Here
let i = 0
is the initialization part as the name suggests, here we initialize a variable after declaring, and this variablelet i = 0
points to the starting point of the loop which means the loop will start from0
.condition: Here
i < 5
is the condition part of the loop, this condition will only return eithertrue
orfalse
. for loop will keep on repeating until the condition returnsfalse
.afterthought: Here
i++
is the afterthought part where we increment the value ofi
after the loop body gets executed every time.
How for loop works:
for(let i = 0 ; i < 2; i++){
console.log('Hello');
}
//Output:
// Hello
// Hello
In the above example, we have initialized i = 0
in the initialization part so the loop will start from 0
. After initialization, condition part i < 2
will be checked, as we know that the value of i
is 0
currently so the condition i < 2
(0 < 2) will be true
and the code inside the block console.log('Hello')
will be executed once.
Now after one execution afterthought part i++
will work and it will update the value of the variable i
(currently 0
) to 1
. After the value is updated ( i = 1
) condition part i < 2
will be checked with the new value of i
and it returns true
as (1<2). As the condition is true
loop will execute the code inside the block console.log('Hello')
for the second time.
Now again after the execution, the value of i
(currently i = 1
) will be updated by the afterthought part i++
again and now the new value of i
will be i = 2
. The updated value i = 2
will be checked by the condition part i<2
which will return false
this time so the loop will stop now.
Note: for loop only works when the condition part is true
.
for loop with arrays:
Let's see how for loop works with arrays.
const array = [1,2,3];
for(let i = 0;i<array.length;i++){
console.log(array[i]);
}
//Output
// 1
// 2
// 3
Here in the initialization part we declared and assigned
let i =0
which will be the starting point of the loop.In condition part
array.length
will give us the length of the array which is3
in the above case so the condition parti<array.length
will returntrue
untili<3
.In the afterthought part
i++
, we are incrementing the value ofi
after each iteration or execution of the loop.In the statement part
console.log(array[i])
, the first iteration will haveconsole.log(array[0])
, the second iteration will haveconsole.log(array[1])
and the third iteration will haveconsole.log(array[2])
.
for loop with objects:
Let us see how to iterate through objects using for loop. But before we start let's see some methods of Object:
- Object.keys() :
Object.keys()
is a method which takes all the keys of an object and stores them in an array.
const info = {
name: 'Abhay',
id: 1234,
color: 'blue'
}
console.log(Object.keys(info));
// Output: ['name','id','color']
In the above example, we got an array of keys by using Object.keys(info)
, now we can use this array to iterate through the keys of the object info
.
- Object.values() :
Object.values()
is a method which takes the values of an object and stores them in an array.
const info = {
name: 'Abhay',
id: 1234,
color: 'blue'
}
console.log(Object.values(info));
//Output: ['Abhay',1234,'blue']
In the above example, we got an array of values of object info
by using Object.values(info)
, now we can use this array to iterate through the values of object info
.
Now we will use these methods to iterate through keys and values of an object using for loop:
Let's understand with an example,
const info = {
name: 'Abhay',
id: 1234,
color: 'blue'
};
for(let i=0; i<Object.keys(info).length; i++){
console.log(Object.keys(info)[i] + ": " + Object.values(info)[i] );
//Object.keys(info)[i] will iterate through the keys ['name','id','color']
//Object.values(info)[i] will iterate through the values ['Abhay',1234,'blue']
};
//Output:
// name: Abhay
// id: 1234
// color: blue
Initialization part:
let i=0
is the initialization part which is the starting point of the array in the above example.condition part: Here we have
i<Object.keys(info).length
as the condition and as we knowObject.keys(info)
will give us an array of keys of the objectinfo
and when we useObject.keys(info).length
then we are taking the length of this array (array of keys of the objectinfo
). So we are running this loop tilli<3
as the array of keys (['name','id','color']
) has length3
.afterthought part: Here we are incrementing the value of
i
after each iteration by1
.statement part: Here we have
console.log(Object.keys(info)[i] + ": " + Object.values(info)[i] )
, first iteration will have
console.log(Object.keys(info)[0] + ": " + Object.values(info)[0] )
this will take value from the array of keys['name','id','color']
and array of values['Abhay',1234,'blue']
at index0
respectively. Similarly, it will iterate through other values of these arrays in each iteration.
for in loop:
for in loop iterates through the keys of an object. Let's see some examples to have a better understanding.
for in loop with objects:
const info = {
name: 'Abhay',
id: 1234,
color: 'blue'
};
for(let key in info){
console.log(key);
}
//Output:
// name
// id
// color
In for in loop, we declare a variable as shown in the above example let key
and then this variable key
iterates through each key of object info
. See how compact the code becomes using for in loop compared to for loop.
We can also iterate through the values of an object.
const info = {
name: 'Abhay',
id: 1234,
color: 'blue'
};
for(let key in info){
console.log(key + ": " + info[key]);
}
//Output:
// name: Abhay
// id: 1234
// color: blue
We did the same example in for loop to iterate through the same object, we can see how compact the code becomes by using for in loop instead of for loop.
for in loop with arrays:
Let's understand with an example:
const arr = [33,22,11,44];
for(let index in arr){
console.log(index);
}
//Output:
// 0
// 1
// 2
// 3
As we can see from the above example, for in loop iterates through the index of an array arr
.
To get the values of the array:
const arr = [33,22,11,44];
for(let index in arr){
console.log(arr[index]);
}
//Output:
// 33
// 22
// 11
// 44
This way we can get the values of the array using for in loop.
for in loop with string:
const str = 'Hello';
for(let i in str){
console.log(i);
}
//Output:
// 0
// 1
// 2
// 3
// 4
In this case also for in loop gives us the index of each character of the string 'Hello'
.
To get the value of the string:
const str = 'Hello';
for(let i in str){
console.log(str[i]);
}
//Output:
// H
// e
// l
// l
// o
This way we can iterate through the characters of the string 'Hello'
.
for of loop:
for of loop is used to iterate through array
and string
.
for of loop with array:
Let's understand with an example:
const arr = [33,22,11,44];
for(let val of arr){
console.log(val);
}
//Output
// 33
// 22
// 11
// 44
As we can see in the above example, we declared variable val
in for of loop which iterates through the values of the array arr
.
for of loop with string:
const str = 'Hello';
for(let i of str){
console.log(i);
}
//Output:
// H
// e
// l
// l
// o
In this way, we can iterate through each character of the string 'Hello'
.
while loop:
while loop repeats a statement or a block of code if the condition defined at the start of the while loop is true
.
For example,
let n = 0;
while(n<3){
console.log(n);
n++;
}
//Output
// 0
// 1
// 2
In the above example, we gave a condition n<3
before the start of the loop body. while loop checks the condition first and if the condition is true
then it runs the code. Inside the loop body, we are printing the value of n
which is 0
for the first iteration and then we are incrementing it n++
.
while loop will keep on executing the code until the value of n
becomes n=3
. At n=3
the condition (n<3)
becomes false
and the while loop stops working.
while loop with array:
const array = [1,2,3,4,5];
let i = 0;
while(i < array.length){
console.log(array[i]);
i++;
}
//Output
// 1
// 2
// 3
// 4
// 5
Here we defined a variable let i = 0
and in the loop we have given the condition i<array.length
, length of array in the above example is 5
so the loop will run until the value of i
becomes 5
.
do while loop:
The only difference between the while loop and the do while loop is that the while loop checks the condition in the starting (before the block starts) whereas the do while loop checks the condition in the end (after the block ends).
For example,
const array = [1,2,3,4,5];
let i = 0;
do{
console.log(array[i]);
i++;
}while (i < array.length)
//Output
// 1
// 2
// 3
// 4
// 5
Same as the while loop, only the condition (i < array.length)
is checked at the end of the block.
while vs do while loop:
Let us see with an example,
while(3<0){ // here the condition is false so the loop will not work
console.log('Orange');
}
// No Output
// here the loop will work at least once as we are checking the condition at the end
do{
console.log('Orange');
}while(3<0)
//Output: Orange
In the above example, while loop is checking the condition at the top (before the start of the block) and as the condition is false
so it will not work.
But in the case of do while loop, it enters the block first, executes the code and after exiting the block it checks the condition while(3<0)
after checking the condition it will stop working as 3<0
is false. Hence code inside the loop body will be executed once.
Summary:
- for loop:
for(statement1;statement2;statement3){
//code to be executed
}
//statement1 is executed only one time.
//statement2 is the condition on which the loop runs.
//statement3 is executed every time after the loop body is executed
for in loop: loops through the keys of an object.
for of loop: loops through the values of an object.
while loop: loops a block of code based on a condition.
do while loop: loops a block of code based on a condition but the condition is defined at the end of the loop body.