JavaScript Programming/While Loops
This lesson introduces JavaScript while and do while loops.
Objectives and Skills
editObjectives and skills for this lesson include:[1]
- Complete and debug loops
- for; while; do; break; continue
Readings
editMultimedia
edit- YouTube: While/do while loop | JavaScript Full Tutorial
- YouTube: JavaScript Tutorial for Beginners - 11 - Loops
- YouTube: #16 While loop in JavaScript
- YouTube: freeCodeCamp.org While / Do While
- YouTube: JavaScript Tutorial For Beginners #16 - While Loops
- YouTube: JavaScript beginner tutorial 21 - do while loop
- YouTube: JavaScript Loops
- YouTube: 4.1: while and for Loops
Examples
editActivities
editComplete 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
editComplete the following using a while loop structure.
- 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
- 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.
- 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)
- 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
editComplete the following using a do while loop structure.
- 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.
- 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.
- 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.
- 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.
- 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- areknawo.com: JavaScript Debugging Done Right
- MDN web docs: The while statement
- For, While and DO While LOOP in JavaScript (with Examples)
- Tutorials Point: JavaScript While Loop
- Difference between JavaScript While and Do While loop
- GeeksforGeeks: Difference Between While and Do-While
- Mozilla: JavaScript Do/While Loop
- W3schools: Javascript While Loop
- sebhastian.com: JavaScript while loop (with examples and use cases)
- W3schools: JavaScript Comparison and Logical Operators
- Programiz: While and Do While Loops Explained
References
edit- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ 2.0 2.1 MDNː Loops and iteration
- ↑ Wikipedia: Don't repeat yourself
- ↑ Craie-programmingː Coding repetition
- ↑ CSULBː CECS 174, Loops
- ↑ Wikipediaː Infinite loop
- ↑ "while - JavaScript | MDN". developer.mozilla.org. Retrieved 2021-02-28.
- ↑ "Increment (++)". MDN Web Docs. Retrieved 2020-09-29.
- ↑ "Decrement (--) - JavaScript | MDN". developer.mozilla.org. Retrieved 2023-02-26.
- ↑ "JavaScript for Loop". www.w3schools.com. Retrieved 2023-02-26.
- ↑ JavaScript.info: While and For
- ↑ MDN: Loops and Iteration
- ↑ W3Schools: JavaScript for loop