- #loops
- #javaScript
What is a loop?
A loop statement in Javascript allows us to repeat a block of code. They are commonly used to loop through, or iterate over, an array of data. It is important that every loop has an end point, otherwise the code will be stuck in an infite loop and the application will break.
There are various kinds of loop. Let’s take a look.
for | for of |
foreach | for in |
while | do while |
for loop
The for loop can iterate an array given a starting point, end point and a counter. The syntax looks like this:
for (start point; end point; counter) {
// statement
}
What happens is that the loop takes the start point (usually 0 for an array), checks that it is not the end point, then performs the statement based on the array element at that position. After the statement has taken place the counter adds to (or takes away from) the start point and process repeats until the end point is reached.
We are going to loop the array called numbers, multiply each element by 2 and push the result into the array called doubledNumbers.
const numbers = [1, 2, 3, 4, 5, 6];
The start point is 0 because the first index of the array is at element 0. The end point is at the end of the array, identified by array.length. After the statement is satisfied, the counter will add 1 to the start point and repeat until the end point is reached.
const doubledNumbers = [];
for (let counter = 0; counter < numbers.length; counter++) {
doubledNumbers.push.(numbers[counter] * 2)
}
// doubledNumbers
// [2, 4, 6, 8, 10, 12]
In this instance, the counter starts at 0 and a checks that it is less than the end point. If so, the statement within the curly braces, if truthy, is performed. The element at numbers[0] is multiplied by 2 and pushed into the doubledNumbers array.
To shorten the code it is common to see use the letter i as the variable name. Within the loop we can add a conditional statement. In the next example, we check to see if an element is even (when divided by 2 the remainder is 0) and if true, push the element to the evenNumbers array.
const evenNumbers = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evenNumbers.push.(numbers[i])
}
}
/// evenNumbers
// [2, 4, 6]
for of
The for of loop, introduced in ES6 requires a variable to be declared before the of keyword, after which the array to be looped is named.
for (let variable of array) {
// do this
}
Note that we cannot define the start or end point, therefore the whole of the array will be iterated over.
const nums = [4, 5, 6];
const tripled = [];
for (let x of nums) {
tripled.push(x * 3);
}
// tripled
// [12, 15, 18]
Conditonal statements can also be used in for of loops.
const nums = [4, 5, 6, 7];
const odd = [];
for (let el of nums) {
if (el % 2 != 0) {
odd.push(el);
}
}
// odd
// [5, 7]
Let us complicated things a little. Create an array of flights planned at an airport. Each flight is an object and the key ‘airborne’ is given a value of true when the aircraft takes off.
const flights = [
{ airline: 'BA', flight: 'BA352', airborne: true, atd: '1100' },
{ airline: 'EasyJet', flight: 'EZ142', airborne: false, atd: '' },
{ airline: 'Al Italia', flight: 'AT762', airborne: false, atd: '' },
];
Using a for of loop we create an array of flights that have departed. The information required in the array is the flight number and actual time of departure (atd).
const departed = [];
for (let el of flights) {
el.airborne && departed.unshift(
{ flight: el.flight, atd: el.atd }
);
}
// departed
// [{flight: 'BA352', atd: '1100'}]
The conditional statement here uses the && syntax. It is called nullish coalescing in other words a ternary operator without else. It runs the code on the right of the && if the statement on the left is true. Otherwise the loop continues.
forEach
The forEach iterator is an array method. It loops over each element in the array and performs a given callback function on each element. Let’s see how forEach compares with a for loop.
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = [];
// for loop
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evenNumbers.push.(numbers[i])
}
}
// forEach
numbers.forEach((el) => {
if (el % 2 === 0) {
evenNumbers.push(el);
}
})
// evenNumbers
// [2, 4, 6]
See how much cleaner and readable the forEach method is in comparison. However, in my experience the original for loop is more powerful. It can contain nested for loops as an example.
I have used all the above loops on a regular basis but there are 2 more that have been around since the beginning of JavaScript. I stray away from them because it is too easy to create an infinite loop! I will mention them briefly.
for in
The for in loop has been around since the early days of JavaScript. Today, the developer’s favourite MDN docs states that “It is better to use a for loop with a numeric index, Array.prototype.forEach(), or the for…of loop, because they will return the index as a number instead of a string, and also avoid non-index properties.” So let’s move on.
while
The syntax is simply:
while (expression) {
statement; // do this
}
The while loop runs the statement if true. Otherwise it stops. For example, log to the console numbers 1 to 5.
let num = 1;
while (num < 6) {
console.log(num);
num++;
}
and finally there is the do while loop.
do while
do {
statement; // do this
} while (expression);
In conclusion there various ways to loops over data and it is well worth playing around to get comfortable with how the work. My go to loops are forEach, for of and the ever faithful for loop. Thanks for stumbling over my notes on and I hope you found something useful here. 👍
Thank you for stumbling across this website and for reading my blog post entitled Loops in JavaScript