Why we haven't covered for-loops

Before this course, you might have worked with arrays before and saw how to iterate over them. If so, you were likely taught at some point to use a a for loop, which looks like this:

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

You might be wondering why we're wrapping up this section, but haven't touched on for loops yet.

Throughout this section, we've seen lots of different array methods that do just the same as a for loop--iterate over an array--but as you now know, they all have specific purposes. We don't have one generic way of performing an iteration. We now know that, given what we want to do with the data, we what array method we use to perform that iteration and to perform a certain operation in the process.

For loops will always be a part of JavaScript and in the previous sections, we saw how to use for of loops, which are very nice and useful. However, what I want to impart in this lesson is that you should aim to use the right tool for the job. This is what learning modern JavaScript is all about--don't use one tool for the job. With the arrival of all these great new features, we don't have to anymore. Use the one most appropriate, that results in the most readable code.

Let's compare this for loop with a code snippet that does exactly the same, but uses an array method we've covered, forEach:

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

numbers.forEach((number) => {
  console.log(number);
});

Which one is easier to write? Which one is easier to read?

So in closing out this section, make full use of the array methods we've covered here, particularly the ones that allow us to create and update arrays immutably:

  • map()
  • filter()
  • reduce()
  • some() / every()
  • find() / findIndex()
  • forEach()

Plus, as a bonus:

  • slice()
  • concat()
  • includes()

And even though it's not an array method, the array spread operator: ...

Review

Master them and the code your write will become simple, more precise, more predictable and ultimately more powerful. JavaScript is a huge language with tons of features. Don't feel obliged to use everything in it. In many cases, like with the for loop, new features have come around to do the same thing better, without a difficult syntax to remember.

So let this be a reminder as you go forward in this course and in your career; you don't need to know all of JavaScript to master it. Look for the features that help you write better code, easier.