Looping Arrays In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Looping Arrays In JavaScript.
Looping Arrays In JavaScript
There are several ways to loop through arrays in JavaScript:
for Loop
A traditional for
loop can be used to loop through an array and access each element one by one.
Example:
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
forEach Loop
forEach
is an array method that allows you to loop through an array and access each element one by one. The forEach
method takes a callback function that is called for each element in the array.
The callback function takes in the current element as its first argument, the index of the current element as its second argument, and the array being looped as its third argument.
Example:
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number, index, numbers) {
console.log(number, index, numbers);
});
for…of Loop
for...of
is a more modern looping construct introduced in ECMAScript 6, that allows you to loop through arrays, maps, sets, and more. The for...of
loop allows you to access each element of the array directly, without having to access it through the index.
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
Conclusion
In summary, forEach
and for...of
are two methods to loop through arrays in JavaScript and access each element one by one. forEach
is useful when you need to access the index of the current element and the array being looped, while for...of
is useful when you only need to access the current element.