DEV Community

Angelo Geant Gaviola
Angelo Geant Gaviola

Posted on

Ways to loop in an array using the different types of "FOR LOOP" in Javascript.

Introduction

As a developer, there are times you are going to encounter handling a set of data.

That means there are times that you have to retrieve them and manipulate them for your program.

Here in this article, I'm going to show you four different ways to loop in an array using the different types of for loops.

For loop (generic)

For loop is a loop that keeps executing itself until the condition gets filled. It also stops when a "break" statement gets executed.

This is what the syntax looks like:

for([variable declaration]; [condition]; [incrementation of the variable]);
Enter fullscreen mode Exit fullscreen mode
  1. The first statement is about the declaration of the variable that you want as a counter --- something that you use to keep count of the iteration.
  2. The second statement is about a condition that you need to get filled before stopping the loop.
  3. The third statement is about adding value to the counter.

Example:

for(counter = 0; counter <3; counter++){
    console.log(counter); // writes to output
};

Output:
0
1
2
Enter fullscreen mode Exit fullscreen mode

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

For in loop

For in loop is a type of "FOR LOOP" that iterates over the indices in a array. It is similar to the normal "FOR LOOP" when executed, however, this is faster to write since it does the sizing of the length and incremental for us.

This is what the syntax looks like:

for(variable in array)
Enter fullscreen mode Exit fullscreen mode

Example:

const grades = [80,85,85,90];

for(let index in grades){
    console.log("Index: "+ index + " -- " + grades[index])
};

Output:
Index: 0 -- 80 
Index: 1 -- 85 
Index: 2 -- 85 
Index: 3 -- 90
Enter fullscreen mode Exit fullscreen mode

Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

For of loop

For of loop is a type of "FOR loop" that iterates over the values in the array.

This is what the syntax looks like:

for(variable of array)
Enter fullscreen mode Exit fullscreen mode

Example:

const grades = [80,86,89,90];
for(let element of grades){
    console.log(element);
}

Output:
80
86
89
90
Enter fullscreen mode Exit fullscreen mode

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Foreach function

Foreach is a method for array structures that takes a callback function for execution.

This is what the syntax looks like:

array.forEach(callbackfn);
Enter fullscreen mode Exit fullscreen mode
  1. array - is the variable that contains your array.
  2. callbackfn - is the callback function taken as an input.

Example:

let array = [1,2,3]
array.forEach((element) => {
    console.log(element);
})

Output:
1
2
3
Enter fullscreen mode Exit fullscreen mode

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Conclusion

As one of my professors said "There are many ways to kill a chicken" depending on what you want to accomplish.

This is my first article, let me know if there's any mistakes or any improvements I should make, Thank you!

Discussion (7)

Collapse
peerreynders profile image
peerreynders

Being an array method .forEach() is really the only one that is limited to arrays.

Note that eslint no-constant-condition won't tolerate while(true) but will accept for(;;).

let count = 0;
for(;;) {
  if (count < 3) {
    console.log(count);
    count += 1;
    continue;
  }

  break;
}
Enter fullscreen mode Exit fullscreen mode

As the reference linked to states:

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

(… and arrays are "special objects")

const special = Symbol('special');
const grades = [];
grades.a = 1;
grades[0] = 80;
grades.c = 3;
grades[1] = 85;
grades.b = 2;
grades[2] = 90;
grades[special] = 42;

console.log(grades[special]);
console.log(grades.hasOwnProperty('1')); // as a string
console.log(grades.hasOwnProperty(1)); // as a number
console.log(grades.hasOwnProperty(special)); // as a symbol

for (const key in grades) {
  console.log(`${keyToString(key)}: ${grades[key]}`);
}

function keyToString(key) {
  switch (typeof key) {
    case 'symbol':
      return 'some symbol';
    case 'string':
      return `'${key}'`;
  }

  return key.toString();
}

console.log('Just keys()');
for (const key of grades.keys()) {
  console.log(`${keyToString(key)}: ${grades[key]}`);
}

/*
42
true
true
true
"'0': 80"
"'1': 85"
"'2': 90"
"'a': 1"
"'c': 3"
"'b': 2"

"Just keys()"
"0: 80"
"1: 85"
"2: 90"

Note how 'in' always produces "string"s
While '.keys()' used with 'of' actually returns "number"s
 */
Enter fullscreen mode Exit fullscreen mode

As the reference linked to states:

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

const special = Symbol('special');
const entries = [
  ['0', 1],
  [0, 80],
  ['2', 3],
  [1, 85],
  ['1', 2],
  [2, 90],
  [special, 42],
];
const someMap = new Map(entries);

for (const [key, value] of someMap) {
  console.log(`${keyToString(key)}: ${value}`);
}

function keyToString(key) {
  switch (typeof key) {
    case 'symbol':
      return 'some symbol';
    case 'string':
      return `'${key}'`;
  }

  return key.toString();
}

/*
"'0': 1"
"0: 80"
"'2': 3"
"1: 85"
"'1': 2"
"2: 90"
"some symbol: 42"
 */
Enter fullscreen mode Exit fullscreen mode

Bonus: Both for...in and .forEach() will skip "holes" ("empty values") in arrays while for...of , .keys() and .entries() will not.

const grades = [80, undefined, , 95]; // hole/empty at index 2

console.log(grades.hasOwnProperty(1)); // true - value undefined
console.log(grades.hasOwnProperty(2)); // false - hole
console.log(grades.hasOwnProperty(3)); // true - number 95

const show = (value, key) => console.log(`${keyToString(key)}: ${value}`);

for (let key = 0; key < grades.length; key += 1) show(grades[key], key);
/*
"0: 80"
"1: undefined"
"2: undefined"
"3: 95"
*/

for (const key in grades) show(grades[key], key);
/*
"'0': 80"
"'1': undefined"
"'3': 95"

i.e. key '2' was skipped
*/

for (const value of grades) console.log(value);
/*
80
undefined
undefined
95
*/

for (const [key, value] of grades.entries()) show(value, key);
/*
"0: 80"
"1: undefined"
"2: undefined"
"3: 95"
*/

grades.forEach(show);
/*
"0: 80"
"1: undefined"
"3: 95"

i.e. index 2 was skipped
*/

function keyToString(key) {
  switch (typeof key) {
    case 'symbol':
      return 'some symbol';
    case 'string':
      return `'${key}'`;
  }

  return key.toString();
}
Enter fullscreen mode Exit fullscreen mode
Collapse
kidxs profile image
Angelo Geant Gaviola Author

Thank you so much for shedding some light!

Collapse
yigitt profile image
yigitt

nice post

Collapse
curiousdev profile image
CuriousDev

Good overview. I think it would be nice for some people to have the first example with an array, because there only "counter" is shown.

Collapse
kidxs profile image
Angelo Geant Gaviola Author

Thank you for the feedback!

Collapse
marynarzswiata profile image
MarynarzSwiata.pl

Nice :) Is always good to know other solution. Thanks. Article saved.

Collapse
curiousdev profile image
CuriousDev

Yes, I agree on this. While one solution is more flexible, another one can make it more readable.