All five loops in JavaScript (and when to use them)
Last updated: July 19, 2022.
Table of contents
How loops work
A loop is a tool that can be used to run some code for each item in an array or array-like object.
They are also very useful for automating repetitive changes.
For example, say you want to capitalize the first letter of all names contained in an array object.
Instead of doing it manually, you can use a loop:
const HPcharacters = ["harry", "hermione", "ron"];
let HPcharactersCapitalized = [];
for (character of HPcharacters) {
// This code runs as many times as there are items in HPcharacters. Each time, character is equal to an item in the array
const capitalizedItem = character.charAt(0).toUpperCase() + character.slice(1); // Capitalizes first letter
HPcharactersCapitalized.push(capitalizedItem); // Pushes to new array
}
console.log(HPcharactersCapitalized); // ["Harry", "Hermione", "Ron"]
If you want to skip one running of the loop, you can use the continue
keyword:
const HPcharacters = ["harry", "hermione", "ron"];
let HPcharactersCapitalized = [];
for (character of HPcharacters) {
if (character === "hermione") {
continue; // skips to next item if item value is "hermione"
} else {
const capitalizedItem = character.charAt(0).toUpperCase() + character.slice(1);
HPcharactersCapitalized.push(capitalizedItem);
}
}
console.log(HPcharactersCapitalized); // [ "Harry", "Ron" ]
To stop the loop completely, use the break
keyword:
const HPcharacters = ["harry", "hermione", "ron"];
let HPcharactersCapitalized = [];
for (character of HPcharacters) {
if (character === "hermione") {
break; // stops loop completely if value is "hermione"
} else {
const capitalizedItem = character.charAt(0).toUpperCase() + character.slice(1);
HPcharactersCapitalized.push(capitalizedItem);
}
}
console.log(HPcharactersCapitalized); // [ "Harry" ]
As you will see, loops in JavaScript vary in their syntax, but all do the same thing: iterate through an array or array-like object and/or automate a repetitive process.
The five loops in JavaScript
#1: The for
loop
With a for
loop, you specify three pieces of information after using the for
keyword, each separated by a semi-colon:
- The starting value of a ‘looping variable’
- A condition for the loop stopping
- A change in the value of the looping variable after each loop is complete
The starting value of the looping variable is typically 0 because JavaScript counts the first item in an array as position 0.
The condition for the loop stopping is typically when all items in an array or array-like object have been looped through. To specify this, access the length
property of the object being looped through and compare this to the value of the looping variable.
Finally, it is typical to increment the value of the looping variable by 1 (i++
) each time so that it corresponds to the index of each item in the object being looped through:
const yearsProgramming = [3,2,3,6,4,2,1];
for (let i = 0; i < yearsProgramming.length; i++) {
console.log(yearsProgramming[i]+1); // 4,3,4,7,5,3,2
}
In this example, each item in the array is being accessed by querying yearsProgramming
in each run of the loop using the value of the looping variable, i
.
for
loop settings don't have to be in the opening parentheses!
The for
loop is very flexible. You can leave parts of the loop specification empty and specify them elsewhere:
const yearsProgramming = [3,2,3,6,4,2,1];
for (let i = 0; i < yearsProgramming.length; // nothing here!) {
console.log(yearsProgramming[i]+1); // 4,3,4,7,5,3,2
i++; // increment in i now done in-loop
}
And here's a more extreme example:
const yearsProgramming = [3,2,3,6,4,2,1];
let i = 0;
for (;;) {
console.log(yearsProgramming[i]+1);
i++;
if(i >= yearsProgramming.length) {
break;
}
}
When to use a for
loop
Use a for
loop when you want to access items in an array or array-like object by their index value and want full control over loop settings.
#2: The for...of
loop
A for...of
loop will run as many times as there are items in the array or array-like object that is specified after the of
keyword.
And you have direct access to the value of each item inside the loop. This is available under the reference name you assign to it before of
.
const yearsProgramming = [3,2,3,6,4,2,1];
for (year of yearsProgramming) {
console.log(year+1); // 4,3,4,7,5,3,2
}
When to use a for...of
loop
Use a for...of
loop when you want to iterate through items in an array or array-like object and want direct access to each value inside the loop.
#3: The for...in
loop
You cannot iterate through a JavaScript object using a for
or for...of
loop because the data stored in one is not numerically ordered (an assumption of loops).
In this regard, the for..in
loop has a very important use: when applied to a custom object, it returns the keys of that object:
const myData = {
javascript: "medium",
python: "easier",
java: "harder",
}
for (key in myData) {
console.log(key); // javascript python java
}
You can then use the key values to access each property value:
const myData = {
javascript: "medium",
python: "easier",
java: "harder",
}
for (key in myData) {
console.log(key); // javascript python java
console.log(myData[key]); // medium, easier, harder
}
When to use a for...in
loop
Use a for...in
loop to extract property values from an object by using the key value available inside the loop.
#4: The do...while
loop
The do...while
loop runs until the while
statement that follows it is false
.
The below loop runs 100 times until the value of visitors
is no longer less than capacity
.
const capacity = 100;
let visitors = 0;
do {
visitors++;
} while (visitors < capacity);
console.log(visitors); // 100
When to use a do...while
loop
Use a do..while
loop for a simple loop that doesn't require access to items in an array or array-like object.
#5: Advanced: async
loops
In the loops above, items are available immediately.
If this is not the case, you can loop through asynchronously using a for await...of
loop. For this, the items must be stored in promises.
const a = new Promise((res) => {
setTimeout(() => {
res("Thanks");
},1000)
})
const b = new Promise((res) => {
setTimeout(() => {
res("For");
},1000)
})
const c = new Promise((res) => {
setTimeout(() => {
res("Waiting");
},1000)
})
const promisesArray = [a,b,c];
async function getData() {
for await (promise of promisesArray) {
console.log(promise); // ... Thanks For Waiting
}
}
getData();
If this doesn't suit your needs, you can still use the await
keyword inside a different loop type:
const a = new Promise((res) => {
setTimeout(() => {
res("Thanks");
},1000)
})
const b = new Promise((res) => {
setTimeout(() => {
res("For");
},1000)
})
const c = new Promise((res) => {
setTimeout(() => {
res("Waiting");
},1000)
})
const promisesArray = [a,b,c];
async function getData() {
for (let i = 0; i < promisesArray.length; i++) {
await promisesArray[i];
console.log(promisesArray[i]); // ... Thanks For Waiting
}
}
getData();
You can read more about async/await and the use of async loops here in our guide to asynchronous JavaScript.
When to use async
loops
When you are looping through items that take time to resolve and are stored in promises.
Related links
- MDN Web Docs: Loops and iteration