for loop & JavaScript

Looping is the most familiar concept in the arena of programming. One of the most basic and most used programming syntax. Throughout this article we will see the different way to loop through array and objects in JavaScript. Computer science is the science of trade-offs and that will our focus while going through various possibilities.


Simple for loop

This is the most familiar way of using for loop for iterating over structures like array where an individual element can be accessed using index based mechanism.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
view raw loop.js hosted with ❤ by GitHub

It is familiar method but the short-coming here is there are too many moving parts. As a programmer in the approach above, we control an index variable represented by i, it’s initial value, boundary condition and finally incremental value of index variable with each iteration.


forEach

This approach is becoming more and more popular with ES6 and onward. It leans towards the functional way of programming. Compared to the for loop we discussed in the section above, it presents very simple & readable programming construct. We focus on the functional programming principle of ‘what to do’ rather than ‘how to do’ stuff with code.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
fruits.forEach(fruit => console.log(fruit));
view raw loop-foreach.js hosted with ❤ by GitHub

Earlier we discussed that we will pick which solution to use within our application based on the trade-offs we have to make upon choosing the solution. If we discuss about choice between for and forEach, one should use forEach as it makes code very simple to understand, it comes with less overhead. But, if you want to skip a step while iterating by using keyword continue or stop the iteration in the midway with the help of keyword break, it is not compatible with forEach loop. Upon using keyword break or continue it will show a syntax error. So one needs to skip a few iteration or break an on-going iteration, for is the right choice.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
fruits.forEach(fruit => {
if(fruit === 'kiwi') {
// A syntax error will be thrown for putting a break statement
// Uncaught Syntax Error: Illegal break statement
break;
}
console.log(fruit)
});
for (let i = 0; i < fruits.length; i++) {
if(fruits[i] === 'kiwi') continue;
console.log(fruits[i]);
}
// output
// apple
// orange
// grapes
// pineapple

for in

Till now, we just focused on array data structure for iteration. With for in we will see that it is designed to iterate over another most used data structure object. An interesting thing to know that in JavaScript, typeof array and any object is object. That means, array is a special case of object. Also, a value of a particular attribute in object can be accessed using index like structure. var obj = { message: 'Hello World!'} can be accessed either using obj.message or obj['message'] where attribute name is passed as string.

Now let’s see how for in helps to iterate over the object. Interesting thing to note is, when we iterate, we receive attribute names but not the attribute value.

const person = {
firstName: 'Virat',
lastName: 'Kohli',
email: 'vk@rcb.in',
profession: 'Cricketer',
team: 'India/RCB'
}
for(attr in person) {
console.log(`Attribute: ${attr} Value: ${person[attr]}`);
}
// Output
// Attribute: firstName Value: Virat
// Attribute: lastName Value: Kohli
// Attribute: email Value: vk@rcb.in
// Attribute: profession Value: Cricketer
// Attribute: team Value: India/RCB
view raw loop-for-in.js hosted with ❤ by GitHub

What happens when we use for in with an array instead of objects? Well, in that case it provides with number keys (array indices) instead of values on the those indices. Shall we use this with array? Well, using for in with array can be a bad idea sometimes. Let’s look at the example below:

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
fruits.code = 'is crazy';
for(e in fruits) {
console.log(e);
}
//Output
// 0
// 1
// 2
// 3
// 4
// code
view raw for-in-array.js hosted with ❤ by GitHub

for of

Another construct iterate over an array is for of. Let’s first how it works.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
for(fruit of fruits) {
console.log(fruit);
}
// Output
// apple
// orange
// kiwi
// grapes
// pineapple
view raw loop-for-of.js hosted with ❤ by GitHub

This approach sits somewhere between standard for and forEach approach. We are not using any extra variable to access any members of data-structure neither data-structure is instructing us on how to iterate on itself. So how it differs? Let’s look at a sample array like const fruits = ['apple', , 'orange', 'kiwi', 'grapes', 'pineapple']; Did you notice the second element on array. It is just blank. Now how forEach and for of will behave in this scenario? Let’s have a look at it.

const fruits = ['apple', , 'orange', 'kiwi', 'grapes', 'pineapple'];
for (fruit of fruits) {
console.log(fruit);
}
// Output
// apple
// undefine
// orange
// kiwi
// grapes
// pineapple
fruits.forEach(f => console.log(f));
// Output
// apple
// orange
// kiwi
// grapes
// pineapple

It is evident from the output that forEach ignore the blank element within the array while for of construct considered the blank element and logged as undefined to the console. So as a programmer we will have to make this choice, are we expect any blank element for the source where we receive the data? If yes, what shall we do with them.


I hope this article helped you understand various way to iterate over object and array data-structure in JavaScript and what trade-offs you make as a programmer when you choose one over another. Let me know your thoughts in comments.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: