Javascript Loops
Written By: Avinash Malhotra
Updated on
Loops and Iteration
JavaScript Loops or looping repeats a piece of code till the particular condition meets. Thus a loop will run a code block again and again until the condition is matched or break. It is one of the easing way to do anything repeatedly.
Imagine we have to print numbers from 1 to 100 or more, we can not write print command 100 times to do this. There loops are helpful. We can call a function n number of times using a loop.
How loops work
The figure above is an example of simple loop where var i=1
is initialization, i<=10
is condition, and i++
is step value. This loop will iterate ten times. After that, it will exit from loop and code will flow.
Type of loops in JavaScript
While Loop
While Loop is Entry Level Loop, which will repeatedly run a code block while a certain condition is true. While keyword works as a condition for loop. If condition is matched, then only loop will iterate.
let i=1;
while(condition){
code block;
}
While Loop Example
let i=1;
while(i<=10){ // iterate 10 times
console.log(i);
i++;
}
In the example above, we've started with a variable declaration i=1. Any variable used inside a loop must be initialized first. If loop is not initialized, this will create syntax error.
The while loop starts with while keyword and condition in parenthesis. while condition says that keep repeating the code block, until i is less than or equal to 5.
i++ is step value, which is increment by 1 in this case. This is very important otherwise it will become Infinite loop. A Infinite Loop can block code flow and hang your computer. 😇
The above loop will print i five times, starting from 1 to 5.
- Initialization, condition and increment are compulsory in while loop.
- If increment is missing, loop will runs Infinitely and system will hang..
- If i=12, and condition is i<=10, loop will never run.
Do While Loop
Do While is exit level loop. This will works even if first condition is false, as condition was checked later. This could be helpful where we wants our loop to run at least once even if the condition is not true.
let i=1;
do{
code block;
}
while(condition)
Do while loop starts with do. While condition will be checked later. This will run code block at least once.
do while This will print first, and then check condition.
Do While Loop Example
let i=12;
do{
console.log(i);
i++;
}
while(i<=10)
The above do while loop starts from 12, while condition is i<=10.
do will work first, and print value of i, i.e. 12.
i++ will increase i value from 12 to 13.
But while condition will terminate loop as i<=10 doesn't match our condition.
- Initialization, condition and increment are compulsory in do while loop.
- If increment is missing, loop will runs Infinitely .
- If i=12, and condition is i<=10, loop will once and print 12.
For Loop
For loop is the most commonly used loop in javascript. Like While loop, for loop also check condition first and then execute, but in a neat and cleaner way.
for( initialization (1); condition (2); step value (4) ){
code block (3);
}
for loop starts with for keyword followed by parenthesis. Initialization, condition and step values are inserted inside. Initialization is declared inside for loop. If the condition is ok, only then the loop will continue.
For Loop Example
2
4
6
8
10
12
14
16
18
20
for( let i=2; i<=20; i=i+2){
console.log(i);
}
The above for loop starts from 2 and the condition is i<=20.
i=i+2 will increase the value of i by 2.
value of i is printed only if condition is matched.
The above loop will return Table of 2.
- Initialization, condition and increment are compulsory in for loop.
- If increment is missing, loop will runs Infinitely .
- If i=12, and condition is i<=10, loop will not work.
break
To break
or terminate a loop or switch in between, we can use break keyword. This will stop further iterations of loop.
loop without break
5
10
for( let i=1; i<=10; i++){
if( i%5==0){ console.log(i);}
}
loop with break
5
for( let i=1; i<=10; i++){
if( i%5==0){ console.log(i); break}
}
continue
continue is used i loop to skip statements executions in current iteration. This means, all the iterations will be executed, except the continue one.
continue example
1
2
4
5
for( let i=1; i<=6; i++){
if( i%3==0){ continue}
console.log(i);
}
Create list using loop
How to create a list in html using loop. We are using for loop to do this. Creating multiple list items in html ins a nightmare. Also they are not dynamic. creating dynamic list using loop can solve this problem. In the example below, we will learn how to do this.
for(let i=1; i<=10; i++ ){
document.querySelector("ol").innerHTML+=`<li>List Item</li>`
}
Create Dropdown list using javascript loop
How to create a select dropdown list using javascript in html. See example below
const x=document.querySelector("select");
for(let i=1; i<=12; i++ ){
x.innerHTML+=`<option> ${i}</option>`
}
Performance Impact of loop
Using loops to create a list of thousand or more elements in html can take more time also can block javascript main thread an can even freeze system. The time taken by loop can vary system to system. Its depends upon the processor. The more powerful processor, less execution time.
Not Recommended
for( let i=1; i<=1000; i++){
document.querySelector("ol").innerHTML+=`<li>List Item ${i}</li>`;
}
Recommended way
let li="";
for( let i=1; i<=1000; i++){
li+=`<li>List Item ${i}</li>`;
}
document.querySelector("ol").innerHTML=li;
Nested For Loop
Nested Loop means a loop inside another loop. We can add one or more loop inside a for loop. The inner loop will execute with multiple iteration on each outer loop iteration. Will See example of Javascript for in loop in next article.
for( initialization; condition; step value ){
for( initialization; condition; step value ){
code block;
}
}
Nested For Loop is used to calculate table of numbers from 1 to 10. Here is an example.
for( let i=1; i<=10; i++){ //10 Times
let tr=document.createElement("tr");
for( let j=1; j<=10; j++){ //10 Times
tr.innerHTML+=`<td>${i*j}</td>`
}
document.querySelector("table").appendChild(tr);
}
In first iteration, when i=1, and j=1, i*j will be 1.
In Second iteration, when i=1, and j=2, i*j will be 2.
In Third iteration, when i=1, and j=3, i*j will be 3.
In 11th iteration, when i=2, and j=1, i*j will be 2.
In 21st iteration, when i=3, and j=1, i*j will be 3.
In last iteration, when i=10, and j=10, i*j will be 100.
For in Loop
for in loop is used in Arrays and Objects. In Array, a for in loop will return index of array. But in Object, for in loop will return key of Object.
For in loop in array
For in loop with array return i as index.
0 "a"
1 "b"
2 "c"
const arr=["a","b","c"];
for( let i in arr){
console.log(i,arr[i]);
}
For in loop in object
For in loop with array return i as key of object.
name foo
id 2
isAlive true
const user={name:"foo", id:2, isAlive:true};
for( let i in user){
console.log(i,user[i]);
}