Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Working with loops

From: JavaScript Essential Training

Video: Working with loops

Very quickly we will find ourselves writing code that we want to have happen multiple times. Whether that's grabbing every paragraph in a page so we can change the background color of it, hiding everything in a menuing system, we will realize there's code we want repeated. Well, rather than write it out multiple times, I'd rather write it once and be able to say, "Repeat this five times," or "Repeat this 5,000 times," or "Just keep on repeating till I tell you otherwise," perhaps go through every single form field on the web page or process every link on a web page in some way, and this is what we do when we are creating loops.

Working with loops

Very quickly we will find ourselves writing code that we want to have happen multiple times. Whether that's grabbing every paragraph in a page so we can change the background color of it, hiding everything in a menuing system, we will realize there's code we want repeated. Well, rather than write it out multiple times, I'd rather write it once and be able to say, "Repeat this five times," or "Repeat this 5,000 times," or "Just keep on repeating till I tell you otherwise," perhaps go through every single form field on the web page or process every link on a web page in some way, and this is what we do when we are creating loops.

You will also hear this referred to as iteration. The main issue with any loop is not when to loop--looping is easy--it's when to stop. If we need to loop 200 times, who is keeping track? If we need to loop until we are told to stop, where is the code to figure out how to stop? But let's first figure out the most basic kind of loop. Well, we've seen if statements before, and this is all I have here. If this condition is true in the parentheses, we will execute the code inside the curly braces.

Now if all I do here is replace the if with the word while, we have a loop. It could be a one line in this code block, there could be 100 lines in this code block; whatever is in the block gets done every time the loop goes around. So we start to run this code. We will create a variable called a, set it equal to 1. We will come down to this while part. I will check the condition, which in this case is a < 10. Yes, that's true. I'll jump into the body of the block, execute any lines of code that are there.

We will hit the end. We will hit the closing brace, and that will jump as back up to the while statement again, where we will ask the same question, is a < 10? Well, yes it is. It's still 1, in which case we'll continue on processing. What we've done here is create a loop. We have actually created an infinite loop, which isn't all that pleasant. It's a bad thing. This would never end. a is always going to be less than 10 because we never change it. So a very common thing that we need to do in most loops is make sure that whatever we are doing to keep track of the loop is being incremented.

So this time I've got an a++ at the end of the body of the loop. So with the of the iteration in place, we will start to increment a every time we go around the loop, and we will keep on going. And at some point, what's going to happen is a will be incremented to 10. We will come back to the while. This will evaluate as false, and then what we'll just do is we will jump out of the loop. We will jump right to the end, and we will continue processing whatever code happens afterwards. Now there is a variant of the while loop called the do while loop.

What this does is keeps the same basic format, but we actually move the condition to the end. So instead of while a is less than 10 being at the start of the block, it's actually at the end of the block, and because of that, we actually need a semicolon at the end of the do while. Now the big difference with this is if you have a do while, the block will always be executed, at least once, even if we started off by setting the variable a equal to 100. And our condition here is asking while a is less than 10, we are going to execute the do block once before we even check the condition.

So it will happen at least once. To let you know, while loops are much more common than these do while loop, and the code I have written over the years I guess that I write at least 100 whiles for every do. In most loops it's expected to check the condition before entering the loop, and it's more readable that way too. Now in many loops a pattern emerges. If I look at a while loop here, I could have a lot of stuff going on in this loop, but I always have to have several pieces in place, regardless of what I am doing.

For a start, I need to have something that keeps track of where I am in the loop, so very typically, before we hit the while loop, we will create an index variable or a counter variable. In this case we will call it i--i is a very common name for an index. So we set up the index, or the counter. We then have to have a place that checks the condition, how do we know whether to keep going through the loop or not, and then in most cases we have to increment the index at the end. So regardless of what we're doing, we need these three pieces in place.

Set up the index, check the condition, increment the index, and this is so common that there is even a shorthand way of doing this, a thing that brings all these together, the for loop. With this, you actually bring those of three pieces together inside the parentheses. They are all there at the top. So regardless of what's in your loop, again it doesn't really matter. Whatever is between the braces will be executed, whether it's simple or complex, but the loop itself has three pieces.

We set up the index, so in this case var i=1. Then there is semicolon. Then we check the condition, i is less than 10, and then, even though it's right at the top, this is the incrementer. This happens at the end of every loop. Now we don't have to go up by 1. You could go up by 4 or 17 or 150 every time if you wanted. So this is very readable because everything about the loop is right there at the top. You don't have to look outside the loop for the index, nor scan inside the loop for the increment.

So the for loop is a very common way of doing this. Now, next up is a couple of words you'll occasionally run into, not as much as the whiles and the fors, but it's worthwhile knowing about them, a word called break. Break is a word that will jump us out of the loop. So let's say we start running our code and we hit this loop. We hit it for the first time through. We set up the index equal to 1. We run the check. Is that less than 5000? Yes, it is. We start to move through the code. We will hit this if segment, for example, and it will say is i=101? No, it isn't.

So we will skip past that code block and continue on, hit the end of the loop, go back up, check the condition again, yes, i is still less than 5000, continue on. Now, at some point what's going to happen is i will be 101. We will hit break. As soon as we hit break, we are basically manually saying we are done. We jump completely out of the loop, and we continue on, regardless of what the condition was at the top, regardless of where our counter was. If we say break, we are done with the loop.

And continue is along the same lines but not quite as drastic. Let's say in this loop, however I've got it set up, I've got some pieces of code. We are doing some stuff. We are checking some options. We are doing a second set of stuff. Well, as we move through the code, if I check this if statement and my counter divided by 5 leaves a remainder of 0, I'll hit that continue; but if it isn't, I will just jump straight ahead and keep going on the second part of the loop. Now at some point again we will jump back.

We will check it, we will start processing, but if ever at any point I actually hit the word continue, that doesn't mean jump out of the loop; it means jump back up and check the condition again. Don't continue any further with this iteration, just this one. We are not done with the entire loop, but we are done with this time around. So we jump right back up, check the condition again, and then start to process. So continue moves us back up to the top. Break moves us out beyond the bottom of the loop.

Now, you won't need continue or break in most loops, but you will see them from time to time, and you need to know what they mean.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 104960 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.