Are you confused among different kinds of loops in Javascript? No worries, I am here to help you out. I will explain every kind of loop in Js in this blog post.
So, lets get started....
We need loops when we want to perform some task repeatedly. Of course you don't want to write the same thing again and again.
Have some pity on your hands. So use loops if you want to save them :)
1.For Loop:
The for loop performs some task until a specified condition becomes false
.
The syntax
of for loop is:
for ([initialExpression];[conditionExpression]; [incrementExpression]){
//code to be executed
}
Initially initialExpression
is executed and then if conditionExpression
return true, then only the code inside the for loop is executed.
And then incrementExpression
is executed. It mostly increment or decrement the counter.
If conditionExpression
returns true, the loop stops right there.
2. While Loop:
The while loop runs until the specified condition returns false
.
Syntax:
while (condition) {
// code to be executed
}
3. Do...While Loop:
The do...while loop runs until a specified condition returns false.
Syntax:
do{
// code to be executed
}
while (condition);
In this loop, the piece of code inside do
block will always get executed atleast once.
Then the condition
inside while is checked. If it returns true
the loop continues to run else the loop stops its execution.
4. For-In Loop:
The for-in statement loops through the properties of an iterable object.
Syntax:
for (variable in object){
//do something
}
It returns the index
of each value inside the object/array.
For Example:
let myFriends = ['vinod','ramesh','arjun','vishal'];
for(let elements in myFriends){
console.log(elements);
}
Output: 0 1 2 3
4. For-Of Loop:
The for-of statement loops through the properties of an iterable object.
Syntax:
for (variable of object){
//do something
}
It returns each value
present inside the object/array.
For Example:
let myFriends = ['vinod','ramesh','arjun','vishal'];
for(let elements of myFriends){
console.log(elements);
}
Output(each in new line): vinod ramesh arjun vishal
This time we are getting values not indexes.
Thats all for now! I hope you enjoyed it reading. Any suggestions or improvements are welcomed.
Top comments (1)
It's not "all" about iteration, what about higer order functions like Array::map and Array::forEach also what about iterator protocol.