Loops
Loops are used in computer science to repeat a sequence of instructions until a condition is met.
JavaScript provides several loop statements. The most common ones are covered below; see MDN’s Loops and iteration guide for the full list.
for loop
A for loop repeats until a specified condition evaluates to false. It has three parts inside its parentheses:
for (initialization; condition; afterthought) {
// statements to repeat
}
initializationruns once, before the loop starts. It usually declares a counter variable, such aslet i = 0.conditionis checked before every iteration. If it is true, the statements in the loop body run; otherwise, the loop ends.afterthoughtruns after each iteration. It usually updates the counter, such asi++. Control then returns to step 2.
A for loop is a common way to step through an array by index:
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}
// 0 apple
// 1 banana
// 2 cherry
Arrays are zero-indexed: the first element is at index 0 and the last is at index fruits.length - 1. That is why the condition is i < fruits.length and not i <= fruits.length — the extra iteration would read fruits[3], which is undefined.
while loop
A while loop runs its statements as long as its condition evaluates to true. The condition is checked before each iteration, so if it is false from the start, the body never runs.
let count = 3;
while (count > 0) {
console.log(count);
count--;
}
// 3
// 2
// 1
Something inside the loop has to eventually make the condition false. Without the count-- line, count would stay 3 and the loop would never end.
do...while loop
A do...while loop works like a while loop, except that the condition is checked after each iteration — so the body always runs at least once.
let i = 0;
do {
i += 1;
console.log(i);
} while (i < 5);
// 1
// 2
// 3
// 4
// 5
for...of loop
A for...of loop goes through the values of an iterable object, such as an Array, a String, a Map, or a Set. It is the most readable choice when you need each element of an array but not its index.
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherry
You can declare the loop variable with const as long as you don’t reassign it inside the loop body. Each iteration gets a new variable.
for...in loop
A for...in loop goes through the property names (keys) of an object. It is useful for looping over the properties of the Objects you create:
const user = { name: 'Ada', role: 'admin' };
for (const key in user) {
console.log(key, user[key]);
}
// name Ada
// role admin
Avoid for...in for arrays. It gives you each index as a string, and it also includes any non-index properties that were added to the array. Use a for loop, for...of, or forEach instead:
const arr = [3, 5, 7];
arr.foo = 'hello';
for (const i in arr) {
console.log(i);
}
// "0" "1" "2" "foo"
for (const i of arr) {
console.log(i);
}
// 3 5 7
break and continue
breakends the loop immediately, and execution continues with the statement after the loop.continueskips the rest of the current iteration and moves on to the next one.
for (let i = 1; i <= 10; i++) {
if (i === 3) {
continue; // skip 3 and go on to the next iteration
}
if (i === 6) {
break; // stop the loop entirely
}
console.log(i);
}
// 1
// 2
// 4
// 5
Arrays also have built-in methods that run a loop for you. The rest of this page covers the most common one, forEach. Unlike the loop statements above, a forEach loop cannot be stopped early with break. If you need to exit early, use a for or for...of loop instead.
forEach loop
There are many different types of loops that you can create in JavaScript, but a popular one is called the forEach loop. This loop allows the computer to iterate over an array (a container of elements) for each element in the list.
The forEach loop calls a callback function on every element in an Array in ascending order.
// Arrow function
forEach((currentValue) => { ... } )
forEach((currentValue, index) => { ... } )
forEach((currentValue, index, array) => { ... } )
// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)
// Inline callback function
forEach(function callbackFn(currentValue) { ... })
forEach(function callbackFn(currentValue, index) { ... })
forEach(function callbackFn(currentValue, index, array){ ... })
forEach(function callbackFn(currentValue, index, array) { ... }, thisArg)
forEach: The name of the method that loops through the elements of an array.currentValue: The current element in the array that is being iterated on. This value will change with every iteration of the method/loop. You can name this parameter any name.index: Holds the index value of the current element that is being iterated on. This is an optional parameter. You can name this parameter any name.array: The array theforEachmethod is iterating onthisArg: Value to use asthiswhen executing callback. You can leave it out when the callback is an arrow function. Arrow functions don’t have their ownthis; they use thethisof the code where they are defined.callbackFn: The function or block of code executed on each method/loop iteration.
As seen above, there are many ways to use the forEach method and define the callback function. The most concise way to define a callback function within the forEach method is through the use of arrow function expressions.
Arrow Functions
Arrow function expressions are a compact alternative to traditional function expressions. They use the symbol => to separate the function’s parameters from its body. Let’s take a look at a few examples comparing traditional functions and arrow functions:
// Traditional Function
function sum(a, b) {
return a + b + 100;
}
// Arrow Function
(a, b) => a + b + 100;
// Traditional Function (no arguments)
let a = 4;
let b = 2;
function sum() {
return a + b + 100;
}
// Arrow Function (no arguments)
() => a + b + 100;
You can practice and explore more with the forEach() method and arrow function expressions in the forEach demo from MDN Docs.