How to properly iterate over an array in JavaScript: forEach, for...of, or a regular for loop?
Hello everyone! I just started learning JavaScript and ran into a problem. I need to go through all the elements of an array and perform some action with them. I know there are many ways, but I'm confused about which one is correct and when to use what.
Here's an example: I have an array of numbers `[1, 2, 3, 4, 5]`, and I want to output each element to the console. I tried several options:
1. Regular `for` loop:
```javascript
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
2. `forEach` method:
```javascript
arr.forEach(function(item) {
console.log(item);
});
```
3. `for...of` loop:
```javascript
for (let item of arr) {
console.log(item);
}
```
All three options work, but I don't understand what the difference is between them. When
No answers yet.
Log in to leave an answer
Blogs