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

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]);
  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

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)

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

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)

Example:

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

Output:
80
86
89
90

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);
  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

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!