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 array.
There are four types of loops in JavaScript.
for loop
while loop
for of loop
for in loop
- The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known.
for (initialization; condition; increment)
{
// code to be executed.
}
e.g. for (let i = 0; i < 5; i++) {
. text += “The number is “ + i + “<br>”;
}
2. The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is not known.
while (condition)
{
// code to be executed.
}
e.g. while (i < 10) {
. text += “The number is “ + i;
. i++;
}
Get Oni Samuel’s stories in your inbox
Join Medium for free to get updates from this writer.
3. The JavaScript for of statement loops through the values of an iterable object. It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more
for (variable of iterable) {
// code to be executed
}
e.g. looping over an array
const cars = [“BMW”, “Volvo”, “Mini”];
let text = “”;
for (let x of cars) {
. text += x;
}
looping over a string
let language = “JavaScript”;
let text = “”;
for (let x of language) {
text += x;
}
4. The JavaScript for in loop is used to iterate the properties of an object.
for (key in object) {
// code to be executed
}
e.g. const person = {fname:”John”, lname:”Doe”, age:25};
let text = “”;
for (let x in person) {
. text += person[x];
}





