JavaScript Loops:-
The JavaScript loops are used to iterate the piece of code using for, while, do-while or for-in loops. It makes the code compact. It is mostly used in arrays.
There are different types of loops:-
1. for Loop:-
Loops through a block of code several
times.
## Syntax.
for(initialization; condition; updateExpression){
statement
}
Example:-
let text = ''
for(let i = 0; i<5; i++){
text = text + i ;
}
console.log(text);
/*0, 1, 2, 3, 4, */
2. while Loop:-
The while loop is to execute code block repeatedly as long as an expression is true
, Once the expression becomes false
the loop terminates.
## Syntax.
while(condition){
statement
}
Example:-
let num = 0;
let n = ''
while(num < 3){
n += num
num++
}
console.log(n)
/* 012 */
3. do...while:-
The do-while
loop is similar to the while loop. This loop will execute the code block once, before checking if the condition is true
, then it will repeat the loop as long as the condition is true
. and condition is false
the loop is terminate.
## Syntax.
do{
statement
}while(condition)
Example:-
let num = 0;
let n = ''
do{
n += num
num++
}while(num < 5)
console.log(n)
/* 01234 */
4. for...in:-
The for...in
loop is used to iterate over all enumerable properties of the object.
## Syntax.
for(let varible in iterate){
statement
}
Example:-
const obj = {
a: "Azaire",
b: "Asher",
c: "Greek"
}
for(const val in obj){
console.log(obj[val])
}
output:-
/*Azaire
Asher
Greek
*/
5. for...of:-
In JavaScript, the for...of
loop is used to iterate over the elements of an iterable object, such as an array.
Syntax.
for(let varible of iterate){
statement
}
Example:-
const Arr = ["Azaire", "Greek", "Asher"]
for(const val of Arr){
console.log(val)
}
output:-
/*
Azaire
Greek
Asher
*/
6. break:-
When inside a loop, if a condition is fulfilled and we don't want to proceed further, we can stop that loop using a break
statement. using break statement
, we break that running loop at that condition fullfiled and stop the other upcoming iterations from occurring.
let's say we run a loop ten
times, and print every iteration number in the console. But we want to stop the printing as soon as we reach the 5th
iteration.
for(let i=0; i<10; i++){
if(i === 5){
break
}
console.log(i)
}
console.log("end")
Output:-
0
1
2
3
4
end
7. continue:-
if a condition is fulfilled inside a loop, and we don't want to run the upcoming code block in that loop at that specific iteration, we use the continue statement. we are jumping over to the next iteration when we use the continue statement.
let's say we run the loop ten times, and print every iteration number in the console. But we don't want the 5th iteration to print the console.
for(let i = 0; i< 10; i++){
if(i === 5){
continue
}
console.log(i)
}
console.log("end")
Output:-
0
1
2
3
4
6
7
8
9
7
end
As you can notice here, the number 5 is not printed. this is because that particular iteration was skipped due to the use of a continue statement.