Javascript Tutorial – Loops with Arrays in Javascript

Loops with Arrays in Javascript

In our last session, we had seen, What is Array and what are different array methods and operators. In this session, We are going to see, how can we use loops with Arrays. We have already seen different types of loops in Javascript in one of our previous session, and today, we will see, How can we use loops with Array. There are different types of loops, that can be used with Array.

Types of Loops with Arrays in Javascript

Let’s see how can we use different for loops in Javascript

  1. for loop
  2. for of loop
  3. for in loop
  4. forEach loop
  5. Array.from

for loop

First and foremost, We will see a normal for loop with Array, that how do we use length property of an array in a normal for loop, and we can run for loop that many times.

let num = [3, 5, 1, 2, 4]
for(let i=0;i<num.length;i++) {
console.log(num[i])
}

for of loop

for of is a loop, where we can get the element of the array, and iterate it through the array.

for (let ele of num) {
console.log(ele)
}

for in loop

for in is a loop, where we can get the index of the array, and iterate it through the array.

for (let i in num) {
console.log(i)
console.log(num[i])
}

forEach loop

forEach is not a loop but it is a method, that acts like a loop, because it iterates for all the elements of the array.
There are 3 ways how we can use a forEach method

  • In the 1st way, We can provide a function or method inside the paranthesis of the forEach method. This is called Higher Order Function, where we provide a function as a parameter to a function. The function that we pass inside the forEach method will have it’s own definition and array element as arguments.
  • In the 2nd way, We can use an arrow function, and we can array element as an argument to that arrow function, and we can write some code inside the arrow function.
  • In the 3rd way, we can use annonymous function, and we will do the same thing we did for arrow function.
let num = [3, 5, 1, 2, 4]
num.forEach(myFunc);

function myFunc(ele) {
  console.log(ele);
}
let num = [3, 5, 1, 2, 4]
num.forEach((ele) => {
  console.log(ele);
})
let num = [3, 5, 1, 2, 4]
num.forEach(function(ele) {
  console.log(ele);
})

Array.from

Array.from is a method or function, It is not a loop.
Array.from converts string into an array.
Array,from returns an array. for example, Array.from returns a character array from a string.
Generally Array.from method is used when we work with HTML Collection, Array.from will create an array from the HTML Collection.

let name = "QAPeddia"
let arr = Array.from(name)
console.log(arr)

Summary

We have covered different types of loops that we can use with Arrays

  1. for loop
  2. forEach loop
  3. Array.from
  4. for of loop
  5. for in loop

Leave a Comment