Home > Web Front-end > JS Tutorial > What are the Different Ways to Loop Through a JavaScript Array?

What are the Different Ways to Loop Through a JavaScript Array?

Susan Sarandon
Release: 2025-01-03 05:51:39
Original
372 people have browsed it

What are the Different Ways to Loop Through a JavaScript Array?

Looping Through an Array Using JavaScript

Iterating through the elements of an array is a common task in JavaScript. There are several approaches available, each with its own strengths and limitations. Let's explore these options:

Arrays

1. for-of Loop (ES2015 )

This loop iterates over the values of an array using an iterator:

const arr = ["a", "b", "c"];
for (const element of arr) {
  console.log(element); // "a", "b", "c"
}
Copy after login

2. forEach

forEach is a method that iterates over the array and calls a function for each element:

arr.forEach(element => {
  console.log(element); // "a", "b", "c"
});
Copy after login

3. Simple for Loop

This loop uses a counter variable to iterate over the array elements:

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]); // "a", "b", "c"
}
Copy after login

4. for-in Loop (with Safeguards)

for-in iterates over an array's properties, which include its elements. However, it's important to use safeguards to avoid iterating over prototype properties:

for (const property in arr) {
  // Check if 'property' is an array element property
  if (arr.hasOwnProperty(property)) {
    console.log(arr[property]); // "a", "b", "c"
  }
}
Copy after login

5. Iterator (ES2015 )

Arrays are iterable objects and provide an iterator that can be manually advanced using next():

const iterator = arr[Symbol.iterator]();
while (true) {
  const result = iterator.next();
  if (result.done) break;
  console.log(result.value); // "a", "b", "c"
}
Copy after login

The above is the detailed content of What are the Different Ways to Loop Through a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template