1 / 10

Understanding For Loops in JavaScript: Basics, Variations, and Output Examples

This guide provides a comprehensive introduction to for loops in JavaScript, specifically using an example that generates output on a web page. Initially, we explore the basic structure of a for loop, which involves initialization, condition, and incrementing the counter. The example displays the phrase "All work and no play makes Jack a dull boy" for 100 iterations. We also discuss variations of the loop, including changing the starting point, counting down, and showing the iteration number within the output. Perfect for beginners wanting to grasp loop mechanics!

jewel
Télécharger la présentation

Understanding For Loops in JavaScript: Basics, Variations, and Output Examples

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to For Loops See Beginning JavaScript (Paul Wilton) p. 87

  2. For Loop Example

  3. Result in browser

  4. var SomeHTML=""; for(i=1; i<=100;i++) { SomeHTML+="All work and no play makes Jack a dull boy. "; } document.write(SomeHTML); for keyword that indicates a for loop repetitive structure i=1 where we start counting the iterations i<=100 condition under which we will continue to count i++ the incrementing — this does the counting, the changing of the counting variable, in this case by 1. It could also be written i=i+1 or i+=1 The parts above are in parentheses and separated by semicolons. Then comes a set a curly brackets. The line(s) of code in the curly brackets constitute a single “iteration.”

  5. Variation There are 3 loops this time; the middle one changes the iteration code (inside the curly brackets) somewhat.

  6. Variation Result

  7. Second Variation The counting variable is concatenated with the text – so that the counting is seen on the page.

  8. Second Variation Result

  9. Third Variation That’s two minus signs in a row. A change in the initialization (starting point) to start at 10, a change in the condition appropriate to counting down, a change from incrementing to decrementing.

  10. Third Variation Result

More Related