Modern JavaScript Fundamentals

JavaScript Loops Extended

Your browser needs to be JavaScript capable to view this video

Try reloading this page, or reviewing your browser settings

This segment delves further into the use of loops, explaining which to use depending on the situation.

Keywords

  • JavaScript
  • js
  • loops. iteration

About this video

Author(s)
Laurence Svekis
First online
11 April 2020
DOI
https://doi.org/10.1007/978-1-4842-5847-7_16
Online ISBN
978-1-4842-5847-7
Publisher
Apress
Copyright information
© Laurence Svekis 2020

Video Transcript

One of the common questions I often get asked about loops is which loop to use and when to use it. So this is going to be a quick lesson on which ones to use, and which ones might be better for depending on the situation, and the differences between the various loop methods in JavaScript.

So we explored that there are different ways to create loops, and loops essentially save us time. It offers us a quick and easy way to do something repeatedly. The most common loop that you’re going to encounter is the for loop. So this is used most commonly. And it essentially loops until the specified condition evaluates to false.

And then there’s the while, and the do while. So these two do have a difference. The do while repeats until a specified condition evaluates to false. The do while loop will always execute at least once. So keep that in mind with the do while loop, that it will always execute at least once. And the while loop is the most basic loop structure. And this one is also condition dependent, so it’s not going to execute unless the condition is true. So that means that it’s not going to run at least one time if the condition is not true. So if we change y to 20, this loop won’t run, whereas if we change z to 20, this loop will run one time.

There’s also best practices, when you are doing loops, and the best practice for when you’re looping out content contained within the arrays is to use the for each loop. Although you can do it either way, and you’ll find that some developers will use the for loop for arrays. And at the end of the day, it just depends on your coding style, and what you want to use, and what fits in best with the code that you’re rating.