Loops in JavaScript
2 min readBy admin

Loops are used to repetitively run a piece of code over and over again without necessarily writing it repeatedly
Loops can execute a certain block of code a number of times.
In programming loops are used to repeat a block of code.
Loops are useful in programming for example when fetching an array of elements from the database
There are five types JavaScript loops
- for loop
- while loop
- do-while loop
- for-in loop
- for-of loop
For loop
The for loops runs over a code of a fixed number of times with a known number of iterations
The syntax is
for(initializer;condition;iterator){
//code
}
- initializer - executes once once the loop begins
- condition - checked before every loop if false loop terminates
- iterator - execute after the body on each iteration
Example a program to print number one to nine using for loop
for(i=0;i<10;i++){
console.log(i)
}
while loop
While loop iterates the elements for infinite number of times and the number of iterations is not known
syntax
while(){
//code
}
Example program to print numbers one to nine using while loop
i = 1
while(i<10){
console.log(i)
i++
}
do .. while loop
It repeats a itself a number of times in a block code just like the while loop, the code is executed at least once whether the condition is true or false
syntax
do{
//code body
} while()
Example program to display numbers one to nine using do.. while loop
i = 0
do{
i++
console.log(i)
} while(i<9)
for in loop
This loop allows you to repetitively run a code over all property keys of an object
Syntax
for(key in object){
// code body
}
Example a program to print numbers one to nine using for in loop
const number = [1,2,3,4,5,6,7,8,9]
for(i in number){
console.log(number[i])
}
for... of loop
The for .. of loop allows you to repetitively run a block of code over iterable objects
The syntax
for(element of iterable){
// code body
}
Example program to print numbers one to nine using for... of loop
const number = [1,2,3,4,5,6,7,8,9]
for(i of number){
console.log(i)
}
You can also learn about JavaScript array methods hereKeep reading
What is Domain-Driven Development?
Software development thrives on approaches that bridge the gap between complex business requirements and technical implementation. Domain-Driven Design (DDD) is one such…
10 Mistakes Developers Make When Building an API (and How to Avoid Them)
APIs (Application Programming Interfaces) are the backbone of modern web development, enabling communication between different software systems. Whether you’re building a RESTful…
How to Build an API using Node.js and Express
Building an API is a fundamental aspect of modern web development, allowing different applications to communicate with each other. In this blog, we'll explore how to build a…
Need A Consultation?
We are here to answer your questions 24/7

