Computer Science

Javascript While Loop

A JavaScript while loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true. It consists of a condition and a block of code. The condition is evaluated before each iteration, and if it is true, the code block is executed.

Written by Perlego with AI-assistance

9 Key excerpts on "Javascript While Loop"

  • Book cover image for: JavaScript for Web Warriors
    • Patrick Carey, Sasha Vodnik, Patrick Carey(Authors)
    • 2021(Publication Date)
    Loop statements in JavaScript include the while, do while, and for statements. ❯ ❯ The while statement is used for repeating a statement or series of statements as long as a given conditional expression evaluates to true. ❯ ❯ Each repetition of a looping statement is called an iteration. ❯ ❯ An infinite loop is a situation in which a loop statement never ends because its conditional expression is never false. ❯ ❯ The do while statement executes a statement or statements once, and then it repeats the execution as long as a given conditional expression evaluates to true. ❯ ❯ The for statement is used to repeat a statement or series of statements as long as a given conditional expression evaluates to true. ❯ ❯ The continue statement halts a looping statement and restarts the loop with a new iteration. ❯ ❯ The process of choosing which code to execute at a given point in an application is known as decision making. In JavaScript, you use the if, if else, else if, and switch statements to create decision-making structures. ❯ ❯ The if statement is used to execute specific programming code if the evaluation of a conditional expression returns a value of true. ❯ ❯ An if statement that includes an else clause is called an if else statement. ❯ ❯ When one decision-making statement is contained within another decision-making statement, they are referred to as nested decision-making structures. ❯ ❯ The switch statement controls program flow by executing a specific set of statements, depending on the value of an expression. ❯ ❯ A break statement is used to exit control statements, such as the switch statement or the while, do while, and for looping statements.
  • Book cover image for: Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    The syntax is as follows: while ( condition ){ //code to be executed } In the following example, you can see a while loop that shows the multiplication table for the num- ber 3. This works based on a counter called i. Every time the while script loops, the counter incre- ments by one. (This uses the ++ arithmetic operator, as you can see from the line that says i++.) So, the first time the script runs the counter is 1, and the loop writes out the line 1 × 3 = 3; the next time it loops around the counter is 2, so the loop writes out 2 × 3 = 6. This continues until the condi- tion—that i is no longer less than 11—is true ( ch10_eg07.js): var i = 1; while ( i < 11 ) { document.getElementById( "numbers" ).innerHTML += "
  • " + i + " x 3 = " + (i * 3) +"
  • "; i ++; } You can see the result of this example in Figure 10-5. Before looking at the next type of loop (a do ... while loop), it is worth noting that a while loop may never run at all because the condition may not be true when it is called. Looping ❘ 361 FIGURE 10-5 do . . . while A do ... while loop executes a block of code once and then checks a condition. For as long as the condition is true, it continues to loop. So, whatever the condition, the loop runs at least once (as you can see the condition is after the instructions). Here is the syntax: do { code to be executed } while (condition) For example, here is the example with the 3 times table again. The counter is set with an initial value of 12, which is higher than required in the condition, so you see the sum 12 × 3 = 36 once, but nothing after that because when it comes to the condition, it has been met ( ch10_eg8.js): var i = 12; do { document.getElementById( "numbers" ).innerHTML += "
  • " + i + " x 3 = " + (i * 3) +"
  • "; i ++; }while (i < 11); Now, if you change the value of the initial counter to 1, you see that the script loops through the multiplication table as it did in the last example until it gets to 11.
  • Book cover image for: Microsoft® Visual C# 2015
    eBook - PDF

    Microsoft® Visual C# 2015

    An Introduction to Object-Oriented Programming

    Within a looping structure, a Boolean expression is evaluated. If it is true , a block of statements called the loop body executes and the Boolean expression is evaluated again. As long as the expression is true , the statements in the loop body continue to execute and the loop-controlling Boolean expression continues to be reevaluated. When the Boolean evaluation is false , the loop ends. Figure 5-1 shows a diagram of the logic of a loop. One execution of any loop is called an iteration . %RROHDQ H[SUHVVLRQ WUXH IDOVH /RRS ERG Figure 5-1 Flowchart of a loop structure You can use a while loop to execute a body of statements continuously as long as the loop’s test condition continues to be true . A while loop consists of the following: • the keyword while • a Boolean expression within parentheses • the loop body The evaluated Boolean expression in a while statement can be either a single Boolean expression or a compound expression that uses ANDs and ORs. The body can be a single statement or any number of statements surrounded by curly braces. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 191 Creating Loops with the while Statement For example, the following code shows an integer declaration followed by a loop that causes the message Hello to display (theoretically) forever because there is no code to end the loop. A loop that never ends is called an infinite loop . An infinite loop might not actually execute infinitely.
  • Book cover image for: Java Programming
    eBook - PDF
    C H A P T E R 6 Looping Upon completion of this chapter, you will be able to: Describe the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops Nest loops Improve loop performance Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 284 Looping C H A P T E R 6 Learning About the Loop Structure If making decisions is what makes programs seem smart, looping is what makes programs seem powerful. A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the loop body executes and the Boolean expression is evaluated again. The loop body can be a single statement, or a block of statements between curly braces. As long as the loop-controlling, Boolean expression is true, the statements in the loop body continue to execute. When the Boolean evaluation is false, the loop ends. One execution of any loop is called an iteration. Figure 6-1 shows a diagram of the logic of a loop. In Java, you can use several mechanisms to create loops. In this chapter, you learn to use three types of loops: • A while loop, in which the loop-controlling Boolean expression is the first statement in the loop, evaluated before the loop body ever executes • A for loop, which is usually used as a concise format in which to execute loops • A do…while loop, in which the loop- controlling Boolean expression is the last statement in the loop, evaluated after the loop body executes one time.
  • Book cover image for: Coding All-in-One For Dummies
    • Chris Minnick(Author)
    • 2022(Publication Date)
    • For Dummies
      (Publisher)
    Listing 6-5 shows a web page containing an example of the while loop. LISTING 6-5: Using a while Loop Guess the Word do . . . while loops The do . . . while loop works in much the same way as the while loop, except that it puts the statements before the expression to test against. The effect is that the statements within a do ... while loop will always execute as least once. Listing 6-6 demonstrates the use of a do ... while loop. LISTING 6-6: Using a do . . . while Loop Let's Count LISTING 6-5: (continued) Getting into the Flow with Loops and Branches CHAPTER 6 Getting into the Flow with Loops and Branches 253 break and continue statements You can use break and continue to interrupt the execution of a loop. The break statement was shown previously in this chapter in the context of a switch state- ment, where it serves to break out of the switch after a successful match. In a loop, break does much the same thing. It causes the program to immediately exit the loop, no matter whether the conditions for the completion of the loop have been met. For example, in Listing 6-7, the word-guessing game will progress just as it does in Listing 6-5, but the loop will immediately terminate if no value is entered.
  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    The statements within a loop constitute the loop body ; the body executes as long as the loop-controlling Boolean expression remains true. The same loop-controlling question is asked following each execution of the loop body; the structure is exited only when the test expression is false. You may hear programmers refer to looping as repetition or iteration . The loop structure in Figure 4-1 is also called a while loop because it fits the following statement: while testCondition continues to be true do someProcess endwhile In pseudocode for the while loop, the endwhile statement clearly shows where the looping structure ends. In Chapter 3, you learned to use endif to perform the same function for a selection structure. All loops can be written as while loops. Most programming languages support an additional loop format called the do-while loop. Appendix D discusses this loop. You encounter examples of looping every day, as in the following example: while you continue to be hungry take another bite of food endwhile or while an unread page remains in the reading assignment read another unread page endwhile In a business application, you might perform tasks like the following: while quantity in inventory remains low continue to order items endwhile or No Yes Figure 4-1 The loop structure 118 C H A P T E R 4 Looping Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
  • Book cover image for: Microsoft Visual C#: An Introduction to Object-Oriented Programming
    Within a looping structure, a Boolean expression is evaluated. If it is true , a block of statements called the loop body executes and the Boolean expression is evaluated again. As long as the expression is true , the statements in the loop body continue to execute and the loop-controlling Boolean expression continues to be reevaluated. When the Boolean evaluation is false , the loop ends. Figure 5-1 shows a diagram of the logic of a loop. One execution of any loop is called an iteration . Figure 5-1 Flowchart of a loop structure Boolean expression true false Loop body You can use a while loop to execute a body of statements continuously as long as the loop’s test condition continues to be true . A while loop consists of the following: • the keyword while • a Boolean expression within parentheses • the loop body The evaluated Boolean expression in a while statement can be either a single Boolean expression or a compound expression that uses ANDs and ORs. The body can be a single statement or any number of statements surrounded by curly braces. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 187 Creating Loops with the while Statement For example, the following code shows an integer declaration followed by a loop that causes the message Hello to display (theoretically) forever because there is no code to end the loop: int number = 1; while(number > 0) WriteLine(Hello); A loop that never ends is called an infinite loop . An infinite loop might not actually execute infinitely.
  • Book cover image for: Python for Beginners
    • Kuldeep Singh Kaswan, Jagjit Singh Dhatterwal, B Balamurugan(Authors)
    • 2023(Publication Date)
    5 Iterative Control Structure
    DOI: 10.1201/9781003202035-5
    Looping is a program or script procedure that performs repetitive (or iterative) tasks. The loop is a sequence of instructions (a block) that is executed repeatedly while or until some condition is met or satisfied. Each repetition is called an iteration. All programming and scripting languages provide loop structures, and, like other languages, Python has several looping constructs [28 ].
    Algorithm design is frequently based on iteration and conditional execution.

    5.1 The While Loop

    The output of Program 5.1 (counting.py) counts up to five.
    print (5) print (4) print (3) print (2) print (1)
    Output 5 4 3 2 1
    How would you write the code to count to 10,000? Would you copy, paste, and modify 10,000 printing statements? You could, but that would be impractical! Counting is such a common activity, and computers routinely count up to very large values, that there must be a better way. What we would really like to do is print the value of a variable (call it count), then increment the variable (count += 1), repeating this process until the variable is large enough (count == 5 or maybe count == 10000). Python has two different keywords, while and for , that enable iteration [29 ].
    Program 5.2 (loopcounting.py) uses the keyword while to count up to five:
    count = 1 while count <= 5: print (count) count += 1
    Output 1 2 3 4 5
    The while keyword in Program 5.2 (loopcounting.py) causes the variable ‘count’ to be repeatedly printed then incremented until its value reaches five. The block of statements
    print(count) count += 1
    is executed five times. After each print of the variable count
  • Book cover image for: Python for Everyone
    • Cay S. Horstmann, Rance D. Necaise(Authors)
    • 2020(Publication Date)
    • Wiley
      (Publisher)
    125 C H A P T E R 4 LOOPS C H A P T E R G O A L S To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To process strings To use a computer for simulations C H A P T E R C O N T E N T S © photo75/iStockphoto. 4.1 THE WHILE LOOP 126 SYN while Statement 127 CE 1 Don’t Think “Are We There Yet?” 130 CE 2 Infinite Loops 130 CE 3 Off-by-One Errors 131 ST 1 Special Form of the print Function 132 C&S The First Bug 132 4.2 PROBLEM SOLVING: HAND-TRACING 133 4.3 APPLICATION: PROCESSING SENTINEL VALUES 135 ST 2 Processing Sentinel Values with a Boolean Variable 138 ST 3 Redirection of Input and Output 138 4.4 PROBLEM SOLVING: STORYBOARDS 139 4.5 COMMON LOOP ALGORITHMS 141 4.6 THE FOR LOOP 145 SYN for Statement 145 SYN for Statement with range Function 146 PT 1 Count Iterations 148 HT 1 Writing a Loop 149 4.7 NESTED LOOPS 152 WE1 Average Exam Grades 155 WE2 A Grade Distribution Histogram 157 4.8 PROCESSING STRINGS 159 4.9 APPLICATION: RANDOM NUMBERS AND SIMULATIONS 164 WE 3 Graphics: Bull’s Eye 167 4.10 GRAPHICS: DIGITAL IMAGE PROCESSING 169 4.11 PROBLEM SOLVING: SOLVE A SIMPLER PROBLEM FIRST 174 C&S Digital Piracy 180 126 In a loop, a part of a program is repeated over and over, until a specific goal is reached. Loops are important for calculations that require repeated steps and for processing input consisting of many data items. In this chapter, you will learn about loop statements in Python, as well as techniques for writing programs that process input and simulate activities in the real world. 4.1 The while Loop In this section, you will learn about loop statements that repeatedly execute instructions until a goal has been reached. Recall the investment problem from Chapter 1. You put $10,000 into a bank account that earns 5 percent inter- est per year.
  • Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.