📌 JavaScript

JavaScript for loops, their uses & trick to remember each

#javascript#for-loops#foreach
December 30, 2021

In programming, the concept of looping is seen to repeat a block of code without actually writing it multiple times and to make it look compact and readable. The concept of implementing a loop remains similar in most programming languages. 

In Javascript, we have quite different ways to implement loops. In this article, we are going to look at the three kinds of Javascript for loops viz., for, for in and for of. Besides for loops there are while, do while and different iterative methods that can be called on arrays to perform looping actions.

For loops in Javascript

JS for loop

The for loop in JS is similar to the C language for loop, it takes three statements, first is initialization, second is condition and third is the update. 

for (Statement 1; Statement 2; Statement 3) {
  // code block
}
  • Statement 1: Initialization of the variable is done using let or var keywords. const cannot be used because variables declared with const cannot be reassigned. 
  • Statement 2: Condition for ending the loop
  • Statement 3: For updating the value of the variable
// A simple for loop to log numbers from 0 to 9
for( let i = 0; i < 10; i++) {
  console.log(i);
}

The first and the third statements can be omitted if those are defined in other parts of the code, but the second statement is important for ending the loop. If the second statement returns true then the loop keeps running if it's false, it stops. When the second statement is also omitted, care has to be taken to break the loop from inside. 

// First and third statements are omitted but are inferred one from outside and the other inside the loop
let i = 0;
for (; i < 5; ) {
  console.log(`Logging ${i}`);
  i++;
}

Using let keyword for for loop doesn't affect the variables declared outside the loop because of the block scope but if var keyword is used for for loop then it may overwrite the values outside the scope.

let i = 5;
for (let i = 0; i < 10; i++) {
  // some code block
}
console.log(i); // The value of i is 5
var i = 5;
for (var i = 0; i < 10; i++) {
  // some code block
}
console.log(i); // 10
// It is 10 because the value of i when loop ends is 10 
// and it is declared with var, so the value persists outside the block

Next, let's see the for-in loop.

JS for-in loop

The Javascript for-in loop is used to iterate over the properties of an object especially the enumerable properties of the object. 

Enumerable properties are those that have enumerable flag set to true when defining the property. By default objects created using {} are enumerable. Find more about it on mozilla.

// for-in loop
for( let key in object) {
  // key gives each key in the object for every iteration
  // code block
}
const countries = {
  norway: 'oslo',
  japan: 'tokyo',
  finland: 'helsinki'
}

// const can be used because it's not being reassigned
for(const country in countries) {
  console.log(countries[country]);
}

// Logs all the values assigned to each country

The for-in loop can also be used for arrays and strings just like objects because the keys for arrays or strings will simply be their indexes. The caveat for using for-in for arrays is that the order of indexes may not be right all the time because those will be treated like the keys in an object and so in the object, the order of the keys is not guaranteed.

const numbers = [10, 9, 8, 7, 6];

for(const index in numbers) {
  console.log(numbers[index])
}

// Index order may not be right all the time
// To understand this, conceive it like an object, 
// where the order of props is not guaranteed
// {
//   '0': 10,
//   '1': 9,
//   '2': 8,
//   '3': 7,
//   '4': 6,
// }

JS for-of loop

The Javascript for-of loop loops over the values of the iterable object. The iterable here cannot be a direct object with key-value pairs because we can't access values directly without their keys. So the iterable in for-of loop refers to an array-like object or a string.

// for-of loop
for( let value of iterable) {
  // value gives each value in the iterable
  // code block
}
const colors  = ['red', 'green', 'pink', 'yellow'];

for(const color of colors) {
  console.log(color); 
}
// All the values from the colors array get logged

Using for-of we can iterate over the letters of a string easily.

const name = 'John';
for(const letter of name) {
  console.log(letter);
}
// Each letter of the string name gets logged

To access the key-value pairs of an object using for-of loop we can use Object.entries method.

const countries = {
  norway: 'oslo',
  japan: 'tokyo',
  finland: 'helsinki',
};

for (const [country, capital] of Object.entries(countries)) {
  console.log(country + ' - ' + capital);
}
// norway - oslo
// japan - tokyo
// finland - helsinki

So that is about for-of loop.

People often get confused in remembering the Javascript for-in and for-of loops.

A simple trick is whenever you see for-in loop think of the second word in as an index which means it can iterate over indexes of an array and the equivalent part in objects is keys. 

In the case of for-of loop, think of of as value belonging to something, in objects values belong to keys, and in arrays just the values directly.

There's one more in Javascript for loops that starts with for, but it is a method that can be called on arrays. Let's have a glimpse at that.

JS forEach for arrays

forEach is a method that can be run on arrays to iterate the values and indexes in their original order. This is the most often used method for looping arrays. 

forEach takes a callback function with three arguments(the last two are optional), that runs on every element of the array.

array.forEach((value, index, array) => {
  // code block
})

Note: forEach doesn't have support for async, await, the results could be not as expected when you await the results inside forEach method. Use for, for-of or for-in loops for asynchronous operations.

That's all about Javascript for-loops. Hope this gave a quick understanding of the differences between each. 

If you like receiving regular tips, tricks related to web development and technology then do follow on devapt-twitter @dev_apt
devapt-github
devapt-twitterdevapt-facebookdevapt-whatsappdevapt-redditdevapt-mail