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 an array in JavaScript, including:
- The
for
loop: This is the most traditional way to loop through an array, and it allows you to access both the index and the value of each element in the array.
var arr = [1, 2, 3, 4, 5];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
- The
forEach()
method: This method allows you to iterate through an array and execute a callback function for each element in the array.
var arr = [1, 2, 3, 4, 5];
arr.forEach(function(value) {
console.log(value);
});
- The
for...of
loop: This looping construct allows you to iterate over the values of an array, without having to reference the index.
const arr = [1, 2, 3, 4, 5];
for (const value of arr) {
console.log(value);
}
- The
for...in
loop: This looping construct allows you to iterate over the properties of an object. It can also be used to iterate over the indexes of an array.
const arr = [1, 2, 3, 4, 5];
for (const index in arr) {
console.log(arr[index]);
}
Conclusion
You can use any of the above method based on your requirement.
If you liked this post Looping Arrays In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.