FOR OF vs. FOR IN vs. FOR EACH

FOR OF vs. FOR IN vs. FOR EACH

By Ifeanyi Omeata

Hi, Let's talk about For of, For in, and ForEach methods of looping through objects. The method we choose is determined by the type of object we wish to loop through and the result we hope to get from the process. Let's go through each of them to see the basic differences.


#1. For...of looping


The For...of statements loop through iterable objects like strings and arrays. The syntax looks like this:

for (variable of iterable) {
  statement
}

Let's see a demo example of iterating through an array:

const arr = ['a', 'b', 'c'];

for (const element of arr) {
  console.log(element);
}

// expected output: "a"
// expected output: "b"
// expected output: "c"

Also, we can iterate through strings:

const str = 'boo';

for (const value of str) {
  console.log(value);
}
// "b"
// "o"
// "o"

Now, let's imagine that we have a string 'str' that we wish to find out if all the letters of the alphabet are found in the string. It means we first have to create an array with all the letters of alphabet:

const str = 'The quick brown fox jumps over the lazy dog.';
const alp = ["a","b","c","d","e","f","g","h","i",'j',"k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

image.png

Next, we would use the for...of statement to loop through the alphabet array to get each element (letter of the alphabet), and within it we would use the includes method to compare if each letter of the alphabet is found in the 'str' string:

const str = 'The quick brown fox jumps over the lazy dog.';
const alp = ["a","b","c","d","e","f","g","h","i",'j',"k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

for (let el of alp) {
  if(str.includes(el)){
    console.log(`${el} is in string.`)
  }else{
     console.log(`${el} is NOT in string.`)
  }
}

image.png

The output will be:

image.png


#2. For...in looping


The For...in statement is quite similar to For...of, the main difference is that it iterates over the properties(keys) of objects or index of Arrays instead of their values. The syntax is similar to that of the For..of looping statement:

for (variable in object) {
  statement
}

Here is a demo of its use:

const obj = { a: 1, b: 2, c: 3 };

for (const prop in obj) {
  console.log(`${prop}: ${obj[prop]}`);
}

// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

Note:
For...in is not recommended to iterate over an Array, especially where the index order is important. It's recommended to use "For...of" or "ForEach" method instead.

"For...in" is mostly used for debugging purposes, especially to check the properties of an object by outputting to a console, or for instances where you want to check if any of the object keys hold a particular value, using something like the "getOwnPropertyNames()", "hasOwnProperty()" or "propertyIsEnumerable()" methods. However, for the sake of our challenge we will still use it to solve the problem.

For our challenge, let's loop through the alphabets using a For...in statement, and then we would output the result:

const str = 'The quick brown fox jumps over the lazy dog.';
const alp = ["a","b","c","d","e","f","g","h","i",'j',"k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

for (let el in alp) {
  console.log(el);
}

image.png

Our output will be:

image.png

What we can see is that it outputs the index position of the alphabets in the array instead of the alphabets(values) themselves. So, to solve this we would use the array bracket notation syntax of declaring values from their index:

const str = 'The quick brown fox jumps over the lazy dog.';
const alp = ["a","b","c","d","e","f","g","h","i",'j',"k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

for (let el in alp) {
  console.log(alp[el]);
}

image.png

So, our output will now be:

image.png

Now, we can use the .includes method to check if each alphabet is found within the given string "str":

const str = 'The quick brown fox jumps over the lazy dog.';
const alp = ["a","b","c","d","e","f","g","h","i",'j',"k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

for (let el in alp) {
  if(str.includes(alp[el])){
    console.log(`${alp[el]} is in string.`)
  }else{
     console.log(`${alp[el]} is NOT in string.`)
  }
}

image.png

The output will now look like this:

image.png


#3. ForEach looping


The Array.prototype.forEach() method is used mostly to iterate through arrays. It calls a specified callback function once for each array element.

The syntax:

// Arrow function
forEach((element) => { ... } )
forEach((element, index) => { ... } )
forEach((element, index, array) => { ... } )

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { ... })
forEach(function(element, index) { ... })
forEach(function(element, index, array){ ... })
forEach(function(element, index, array) { ... }, thisArg)

Here is a demo of a forEach statement:

const arr = ['a', 'b', 'c'];

arr.forEach(el => console.log(el));

// expected output: "a"
// expected output: "b"
// expected output: "c"

So, let's use ForEach method to loop through alphabets for our challenge, then we would compare each of the alphabets with our string "str" using the .includes method, to see if all the alphabets are contained in the string:

const str = 'The quick brown fox jumps over the lazy dog.';
const alp = ["a","b","c","d","e","f","g","h","i",'j',"k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

alp.forEach((el) => {
  if(str.includes(el)){
    console.log(`${el} is in string.`)
  }else{
     console.log(`${el} is NOT in string.`)
  }
})

image.png

Our output will be:

image.png

Summary:
In general, I actually prefer to use For...of looping statements than the other two, because it gives me more options to loop through many types of iterable items; unlike ForEach which is mainly suitable for looping through arrays, and For..in which is mainly used for debugging. The For...of looping method is also very concise and feels more modern in use. So, to me, For...of wins the day! But you can use whatever you want to use tbh. :)

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2021