JavaScript Programming/While Loops

This lesson introduces JavaScript while and do while 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. Wikibooks: JavaScript/Control structures
  3. Techdifferences: Difference Between while and do-while Loop

Multimedia

edit
  1. YouTube: While/do while loop | JavaScript Full Tutorial
  2. YouTube: JavaScript Tutorial for Beginners - 11 - Loops
  3. YouTube: #16 While loop in JavaScript
  4. YouTube: freeCodeCamp.org While / Do While
  5. YouTube: JavaScript Tutorial For Beginners #16 - While Loops
  6. YouTube: JavaScript beginner tutorial 21 - do while loop
  7. YouTube: JavaScript Loops
  8. YouTube: 4.1: while and for Loops

Examples

edit

Activities

edit

Complete one the following activities in each category of loop 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.

While Loops

edit

Complete the following using a while 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: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.
  3. 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 using a prompt and add it to a total. Finally, calculate and display the average for the entered scores. (This might be helpful: Get Number from Prompt Input)
  4. 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 request each score using an input element and add it to a total. Finally, calculate and display the average for the entered scores. In this approach, the loop action is performed by the user rather than by the code. Use hidden elements to keep track of the total and count.

Do While Loops

edit

Complete the following using a do while loop structure.

  1. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Use a loop to request each score using a prompt and add it to a total. Continue accepting scores until the user enters no value (empty input). Finally, calculate and display the average for the entered scores.
  2. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess using a prompt. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program.
  3. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Request each score using an input element and add it to a total. Continue accepting scores until the user enters no value (empty input). Finally, calculate and display the average for the entered scores. In this approach, the loop action is performed by the user rather than by the code. Use hidden elements to keep track of the total and count.
  4. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess using three buttons. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program. In this approach, the loop action is performed by the user rather than by the code.

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]
  • A nested loop, or a loop inside of another loop, can be used to better structure code and make it maintainable; but can present performance issues in larger applications.[source?]
  • A "for" loop is set to run a set number of times or until a certain condition is met.
  • A "while" loop is set to run as long as a certain expression evaluates to true.
  • In a while loop, the condition is checked before any statement in the loop is executed, where as a do while loop will execute the statements once before checking the condition. [7]

Key Terms

edit
Increment
The increment operator (++) increments (adds one to) its operand and returns a value.[8]
Decrement
the Decrement operator (--) decrements (subtracts one from) its operand and returns a value.[9]
do while loop
This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.[10]
Infinite loop
A loop that theoretically runs forever.[11]
Iteration
It's a repetition of code or cycle, performed by a loop[12]
while loop
The while loop executes a block of code repeatedly as long as a specified condition is true.[13]

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. "while - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-02-28.
  8. "Increment (++)". MDN Web Docs. Retrieved 2020-09-29.
  9. "Decrement (--) - JavaScript | MDN". developer.mozilla.org. Retrieved 2023-02-26.
  10. "JavaScript for Loop". www.w3schools.com. Retrieved 2023-02-26.
  11. JavaScript.info: While and For
  12. MDN: Loops and Iteration
  13. W3Schools: JavaScript for loop