Iterating over array elements is a fundamental skill in JavaScript programming. It allows us to access and perform operations on each element of an array.
When iterating over an array, we can use various techniques such as:
- The
for
loop: One common way to iterate over an array is by using afor
loop. This loop allows us to iterate over each element of the array using an index.
JAVASCRIPT
1const myArray = [1, 2, 3, 4, 5];
2
3for (let i = 0; i < myArray.length; i++) {
4 console.log(myArray[i]);
5}
- The
forEach
method: JavaScript provides theforEach
method, which is a more concise way to iterate over an array. It allows us to pass a callback function as an argument, which will be executed for each element of the array.
JAVASCRIPT
1const myArray = [1, 2, 3, 4, 5];
2
3myArray.forEach((element) => {
4 console.log(element);
5});
- The
for...of
loop: Introduced in ES6, thefor...of
loop is another approach to iterate over arrays. It allows us to directly access each element of the array without using an index.
JAVASCRIPT
1const myArray = [1, 2, 3, 4, 5];
2
3for (let element of myArray) {
4 console.log(element);
5}
These are just a few techniques for iterating over arrays in JavaScript. Understanding how to iterate over arrays is essential for performing operations on array elements and manipulating data.
xxxxxxxxxx
20
// Iterating over an array using a for loop
const myArray = [1, 2, 3, 4, 5];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
// Iterating over an array using the forEach method
const myArray = [1, 2, 3, 4, 5];
myArray.forEach((element) => {
console.log(element);
});
// Iterating over an array using the for...of loop
const myArray = [1, 2, 3, 4, 5];
for (let element of myArray) {
console.log(element);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment