Loops in JavaScript
JavaScript loops
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 here