JavaScript Programming/For Loops

This lesson introduces JavaScript for loops and nested loops.

Objectives and Skills

edit

Objectives and skills for this lesson include:[1]

  • Complete and debug loops
    • for; while; do; break; continue

Readings

edit
  1. Wikipedia: Control flow
  2. Wikipedia: For loop

Multimedia

edit
  1. YouTube: JavaScript Tutorial for Beginners - 28 - getElementsByTagName Part 2
  2. Youtube: For Loops | Javascript | Tutorial 23
  3. YouTube: #17 For Loop in JavaScript
  4. YouTube: For Loops - Beau teaches JavaScript
  5. YouTube: JavaScript Tutorial for Beginners - 12 - Loops Part 2
  6. YouTube: JavaScript Tutorials for Beginners - 9 - How to Code Nested For Loops with JavaScript
  7. Youtube: JavaScript Nested Loops
  8. YouTube: #18 While vs For Loop | Which to use and When?
  9. JavaScript Loops

Examples

edit

Activities

edit

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, indentations, naming conventions, and constants. Use input elements for input and respond to input or change events or add buttons and respond to click events. Use HTML elements for output. Use separate functions for each type of processing. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

For Loops

edit

Complete the following using a for loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
        1 * 1 = 1
        1 * 2 = 2
        1 * 3 = 3
    A list of five expressions for the value 3 would be:
        3 * 1 = 3
        3 * 2 = 6
        3 * 3 = 9
        3 * 4 = 12
        3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.

Nested Loops

edit

Complete the following using a nested loop structure.

  1. Review MathsIsFun: 10x Printable Multiplication Table. Create a program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels. For example, the output from 1 to 3 might look like:
            1   2   3
        1   1   2   3
        2   2   4   6
        3   3   6   9
    The output from 3 to 5 might look like:
            3   4   5
        3   9  12  15
        4  12  16  20
        5  15  20  25

Lesson Summary

edit
  • Loops are used to avoid code repetition.[2]
  • Loops are useful when aiming for DRY (Don't repeat yourself) solutions vs. WET (Write every time) solutions when programming.[3]
  • Four components of any loop are the initialization of a loop control variable, terminating condition, update step (increment or decrement), and a loop body.[4][5]
  • Loop may run n number of times or may not run at all, depending on the condition.[2]
  • We get an infinite loop when we forget to include terminating condition, when the condition can never be met or if it makes the loop to start over and over again.[6]
  • Loops are handy, if you want to run the same code over and over again, each time with a different value.[7]
  • The basic structure for a for loop is: for (initialExpression, condition, increment) {loop body} ;[source?]
  • If you omit statement 2 (condition), you must provide a break inside the loop. Otherwise the loop will never end.[8]
  • Statement 3 (increment) can do anything like negative increment (i--), positive increment (i = i + 15), or anything else. Statement 3 can also be omitted.[9]
  • For loops can be run from n-n number of times (ie. 3-8) meaning you can skip the data for a set number of loops. This isn't possible with other loops.[10]
  • Continue only skips one iteration in the loop, where as break statements leave the loop completely.[source?]

Key Terms

edit
break
A statement used to jump out of a loop.[11]
continue
A statement where it breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.[12]
for loop
Loops repeatedly executes a block of code a specified number of times.[13]
for/in loop
loops through the properties of an object.[13]
for/of loop
loops through the values of an iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.[13]
loop counter
A variable that controls how many iterations of a loop occurs. [14]
nested loops
A composition of loops is called a nested loop. The most common type of nested loops will be one loop inside another. The first loop is usually called the outer loop while the second loop is called the inner loop.[15]

See Also

edit

References

edit
  1. Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. 2.0 2.1 MDNː Loops and iteration
  3. Wikipedia: Don't repeat yourself
  4. Craie-programmingː Coding repetition
  5. CSULBː CECS 174, Loops
  6. Wikipediaː Infinite loop
  7. W3Schools: JavaScript For Loop
  8. W3Schools: JavaScript For Loop
  9. W3Schools: JavaScript For Loop
  10. FreeCodeCamp: JavaScript Loops Explained
  11. W3Schools: JavaScript break
  12. "JavaScript Break and Continue". www.w3schools.com. Retrieved 2020-10-06.
  13. 13.0 13.1 13.2 W3Schools: JavaScript for loop
  14. "For loop". Wikipedia. 2021-02-17. https://en.wikipedia.org/w/index.php?title=For_loop&oldid=1007384841. 
  15. EXL Skills: JavaScript Nested Loops