JavaScript Loop Which Made Life Easy — JS Startup
In this tutorial, you’ll be going to learn a javascript loop which is for loop, while loop, and do-while loop. All three of them are like a legend that you will found in most of the language.
But javascript also introduces two other newcomers which help in especially dealing with an array, object, map, set, etc like stuff. So here, they are for…of loop and for…in loop.
JavaScript Loop
The javaScript loop’s main task is to repeat a certain block of code until a certain condition is fully filled. As I already mentioned above 5 types of a loop which we will be going to discuss in detail.
But all have their own of dealing with string, array, object, map, set, etc. Loops can execute a block of code a number of times.
When the developer talks about iteration or iterating over the string, array, object, etc. It’s actually the same as looping.
JavaScript loop is a highly used code in day-to-day task and project requirements which definitely made life easy. Let’s start to learn all the javascript loop in detail.
Want to learn something more
1. JavaScript for loop
for loop is currently the most used looping execute a certain block of code repeatedly based on condition pass to for loop. Why it’s mostly used because it’s the first loop we learn and it’s easy to use compared to others.
for loop Syntax
for (initialization; test condition; iteration statement) {
// code block to be executed until test condition is true
}
Some Example of Javascript for loop
Here, you’ll learn some use cases or examples of for loop.
Basic Example of for loop
for(let i = 0; i < 5; i++){
console.log(i);
} // 0, 1, 2, 3, 4
Iterate array with for loop
Here, we loop over an array until all elements in that array get printed. Which means up to the length of the array.
const array = [10, 20, 30, 40, 50]; for(let i = 0; i < array.length; i++){
console.log(array[i]);
}// 10, 20, 30, 40, 50
Iterate string with for loop
The string is also an iterable value like an array up to the length of the string.
let name = "JS Startup"; for(let i = 0; i < name.length; i++){
console.log(name[i]);
} // J,S, ,S,t,a,r,t,u,p
At last, there is a lot of stuff that you can do with for loop like pattern printing, modify array and object values, etc.
Note: The wrong statement in the for loop statement sometimes leads to an infinite loop.
2. JavaScript While Loop
while loop also helps to accomplish the same thing which can for loop does. while loop loops through a block of code while a specified condition is true.
Compare to for loop, while loop only contains one statement rather than 3 statements. But that statement still exist outside or inside of a while loop.
while loop Syntax
In the below, while loop syntax, you can see there is only condition pass to while nothing else. If the condition is true then it executes a block of code.
while (condition) {
// code block to be executed until condition return true
}
Some Example of Javascript while loop
Basic Example of while loop
let i = 0; while(i < 5){
console.log(i); i++;
} // 0, 1, 2, 3, 4
Iterate array with a while loop
Here, we use while loop over an array until all elements in that array get printed. Which means up to the length of the array.
const array = [10, 20, 30, 40, 50]; let i = 0; while(i < array.length){
console.log(array[i]);
i++;
} // 10, 20, 30, 40, 50
Iterate string with a while loop
The same goes for string also because the string is an iterable value like an array.
let name = "JS Startup"; let i = 0; while(i < name.length){
console.log(name[i]);
i++
} // J,S, ,S,t,a,r,t,u,p
Comparing for and while Loop
Both loops works the same as you can see the output. The only difference is the placement of statements. But mostly, everyone prefers for loop as you can define all the statements in one place.
Let’s take one example of each in for loop & while loop looks the same.
let array = ["Hi" "JS", "Startup"]; let i = 0; for (;array[i];) {
console.log(array[i])
i++;
} // Hi, JS, Startuplet array = ["Hi" "JS", "Startup"];let i = 0; while (array[i]) {
console.log(array[i])
i++;
} // Hi, JS, Startup
Above both, the example runs until there is a value in the array and they look similar to for also only contain conditional statement.
3. JavaScript do-while loop
In javascript, do-while is a variant of while loop as while loop still in the do-while. Like for loop and while loop, which never runs until condition satisfied that not the condition with do-while.
do-while loop syntax
do{
// code block to be executed once then based on while condition
} while (condition)
Some Example of Javascript while loop
Here, you’ll learn some use cases or examples of a do-while loop. We can use the same example as above but do while loop gives the same output if all condition is true. But if the condition failed in the first occurrence then output is changed.
Basic Example of the do-while loop with a true condition
let i = 0; do {
console.log(i);
i++;
} while(i < 5) // 0, 1, 2, 3, 4
Basic Example of the do-while loop with a false condition
Now, we use the same example as above but instead of 5, we use 0. If it’s a or while loop code not even runs. But that, not the case with a do-while loop.
let i = 0; do {
console.log(i);
i++;
} while(i < 0) // 0
As you can see we get a 0 because do block run once then it checks for failed condition Which stops the execution.
You can check the same scenario with array and string also if everything is fine then it gave the same result as for and while loop. But if the condition returns false then the output of for and while loop not matches with do-while.
Welcome Newcomer
Above, three loops can find out in, etc but javascript also introduces two new loops which are and because we web developers mainly deals with iterable types value like array & object.
Wait, Want to dig in more into javascript
4. JavaScript for…of loop
In javascript, for…of loop loops through a value of iterable objects like Array, Map, Set, String, arguments, etc.
Note: This loop iterated over property values.
for…of loop syntax
In this, we have a variable which contains the value of iterable object like an array, map, set, etc. And it’s value changes as the loop iterate until the length of iterable.
for (variable of iterable) { statement }
Some Example of Javascript for…of loop
Iterating string with for…of loop
In the below example, we use a string “jsstartup” and iterate over it and get each character separately.
const name = 'jsstartup'; for (const char of name) {
console.log(char);
} // 'j','s','s','t','a','r','t','u','p'
Iterating array with for…of loop
Now, we use an array to loop through and like other loops here we just need one variable which contains a value of the array at each iteration.
const array = [10, 20, 30, 40]; for (const value of array) {
console.log(value);
} // 10, 20, 30, 40
Iterating Map with for…of loop
The Map object is iterable over its key and value pairs. A map is like an object.
const map = new Map(); map.set('name', 'JS');
map.set('value', 'Startup'); for (const [key, value] of map) {
console.log(key, value);
} // 'name', 'JS'
// 'value', 'Startup'
Iterating Set with for…of loop
The Set
an object is iterable over its items. Set is like an array but only store unique values in it.
const set = new Set(['Hi', 'Ajay', 'Yadav']); for (const item of set) {
console.log(item);
} // 'Hi', 'Ajay', 'Yadav'
Iterating arguments with for…of loop
You can iterate over the arguments object to examine all of the parameters passed to it.
(function() {
for (const argument of arguments) {
console.log(argument);
}
})(10, 20, 30); // 10, 20, 30
5. JavaScript for…in loop
In javascript, you have so many loops to iterate over a string, array, map, set, arguments, etc. But what about the javascript object because it also needs to be iterate like others.
Before the for..in loop, it’s very difficult to iterate over it. But now, it’s easy as for…of loop. for…in loop loops through the properties of an object and array. But with an array, it’s not recommended to use for..in.
Note: This loop iterated over the property name.
for…in loop syntax
In this, we also have a variable but it contains the property of object & array. And it’s value changes as the loop iterate until the no of a key in the object and index in the array.
for (variable in object){
statement
}
Some Example of Javascript for…in loop
Here, you’ll learn some use cases or examples of a for…in loop. We can use the same example above like using an array and object but not a string.
Iterating object with for…in
In the below example, we iterate an object with two keys and variables contain the key of the object which changes in each iteration.
const detail = { name : "JS", phone : "+91" } for(const property in detail){
console.log(property, detail[property]);
} // "name", "JS"
// "phone", "+91"
Note:for...in
should not be used to iterate over an Array where the index order is important. According to Mozilla.
Iterating array with for…in (Not Recommended)
const array = ["JS", "Startup"]; for(const index in array){
console.log(index, array[index]);
} // "0", "JS"
// "1", "Startup"
Finally, I hope you like all the loops and know when to use which loop. Because as technology progress it’s better to keep in touch with it.
Check out our daily javascript quiz
- JavaScript Quiz — array map converts an element value with parseInt
- JS Quiz — does the splice method replace array element
- JS Quiz — is the console log function really override
- JavaScript Quiz — delete work on object create method object
Conclusion
To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
Important: If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.
If you like this article please give me a clap.
Originally published at https://jsstartup.com on October 20, 2020.