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.
Let’s see how can we use different for loops in Javascript
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 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 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 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
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 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)
We have covered different types of loops that we can use with Arrays
Objects, Classes and Constructor in Javascript Classes and Objects A class in any programming language…
We will start from object oriented programming basics like What are different concepts in Object…
Why we can not over ride a Constructor This is a very important question, that,…
What is Arrow Function In the last session, We had discussed about Anonymous Function. Anonymous…
What is Anonymous Function Anonymous Function is a type of function which has no name…
What is Map, Reduce and Filter Map Filter and Reduce are higher order methods for…