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"

  • JavaScript from Beginner to Professional
    • Laurence Lars Svekis, Maaike van Putten, Codestars By Rob Percival(Authors)
    • 2021(Publication Date)
    • Packt Publishing
      (Publisher)

    5

    Loops

    We are starting to get a good basic grasp of JavaScript. This chapter will focus on a very important control flow concept: loops. Loops execute a code block a certain number of times. We can use loops to do many things, such as repeating operations a number of times and iterating over data sets, arrays, and objects. Whenever you feel the need to copy a little piece of code and place it right underneath where you copied it from, you should probably be using a loop instead.
    We will first discuss the basics of loops, then continue to discuss nesting loops, which is basically using loops inside loops. Also, we will explain looping over two complex constructs we have seen, arrays and objects. And finally, we will introduce two keywords related to loops, break and continue , to control the flow of the loop even more.
    There is one topic that is closely related to loops that is not in this chapter. This is the built-in foreach method. We can use this method to loop over arrays, when we can use an arrow function. Since we won't discuss these until the next chapter, foreach is not included here.
    These are the different loops we will be discussing in this chapter:
    • while loop
    • do while loop
    • for loop
    • for in
    • for of loop
    Note: exercise, project, and self-check quiz answers can be found in the Appendix .

    while loops

    The first loop we will discuss is the while loop . A while loop executes a certain block of code as long as an expression evaluates to true . The snippet below demonstrates the syntax of the while
  • Processing
    eBook - ePub

    Processing

    An Introduction to Programming

    5
    Repetition with a Loop: The  while    Statement    
    We have seen in the programs we have written that the order in which the statements are written makes a difference. This illustrates a key principle of computing known as sequence  .
    In Chapter  4, we saw that statements placed inside an if  or switch  statement are only performed if a certain condition is true. Such conditional programming illustrates a second key principle of computing known as selection  .
    In this chapter and the next, we will see that, sometimes, one or more statements need to be performed repeatedly   in a computer program. This will illustrate a third key principle in computing: repetition  .
    Human beings often find repetitive tasks to be tedious. In contrast, computers can provide an ideal way to perform repetitive tasks.  Repetition as Long as a Certain Condition Is True
    Like the if  statement, each repetition structure in this chapter will make use of a condition  . This condition will determine whether the repetition should continue  .
    Once again, let’ s consider a cooking recipe as an analogy to a computer program. Suppose a certain dough recipe says that you are to mix the ingredients and then repeatedly   add ½  cup of flour as long as   you can still stir the mixture with a spoon. A flowchart of this recipe might look like the following:
    Similarly, in computer programming, there are sometimes sets of statements that we would like to perform repeatedly  , but only as long as   a certain condition is true.
    Repetition with the while   Statement
    Processing provides several programming structures that can be used for creating repetition. One of the more versatile of these repetition structures is the while   statement. The basic form of the while
  • HTML5 and CSS3 All-in-One For Dummies
    • Andy Harris(Author)
    • 2014(Publication Date)
    • For Dummies
      (Publisher)
    endless loops are especially troubling in JavaScript because they can crash the entire browser. If a JavaScript program gets into an endless loop, often the only solution is to use the operating system task manager (Ctrl+Alt+Delete on Windows) to shut down the entire browser.
    The easy way to make sure your loop works is to remember that while loops need all the same features as for loops. (These ideas are built into the structure of a for loop. You're responsible for them yourself in a while loop.) If your loop doesn't work, check that you've followed these steps:
    • Identify a key variable: A while loop is normally based on a condition, which is usually a comparison (although it might also be a variable or function that returns a Boolean value). In a for loop, the key variable is almost always an integer. While loops can be based on any type of variable.
    • Initialize the variable before the loop: Before the loop begins, set up the initial value of the key variable to ensure the loop happens at least once. (How does the variable start?)
    • Identify the condition for the loop: A while loop is based on a condition. Define the condition so the loop continues while the condition is true , and exits when the condition is evaluated to false . (How does the variable end?)
    • Change the condition inside the loop: Somewhere inside the loop code, you need to have statements that will eventually make the condition false . If you forget this part, your loop will never end. (How does the variable change?)
    This example is a good example of a while loop, but a terrible way to handle security. The password is shown in the clear, and anybody could view the source code to see the correct password. There are far better ways to handle security, but this is the cleanest example of a while
  • Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    ch10_eg07.js ):
    var i = 1; while ( i < 11 ) { document.getElementById( "numbers" ).innerHTML += "<li>" + i + " x 3 = " + (i * 3) +"</li>"; 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.
    start figure
    Figure 10-5
    end figure

    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 += "<li>" + i + " x 3 = " + (i * 3) +"</li>"; i ++; }while (i < 11);
  • JavaScript For Kids For Dummies
    • Chris Minnick, Eva Holland(Authors)
    • 2015(Publication Date)
    • For Dummies
      (Publisher)
    while loops carefully to make sure they’re not infinite!
    A while loop can do everything that a for loop can do, but the coding is just a bit different. Let’s take a look at the three uses for for loops that we talk about in Chapter 17 and show how to do them with while .

    Looping a certain number of times

    Listing 18-1 shows how you can use a while loop to log Hello, JavaScript! to the console window 500 times.
    Listing 18-1 Logging Hello, JavaScript
    var i = 0; while (i < 500) {     console.log(i + ": Hello, JavaScript!");     i++; }
    Notice that the program in Listing 18-1 contains all the same three parts that are in a for loop (initialization, condition, and final expression), but only the condition is inside the parentheses. The initialization (var i = 0; ) is before the while loop, and the final expression (i++ ) is inside the while loop.

    Counting with while

    To create a loop that counts, you can just modify a variable inside every pass through the loop and use that variable inside other statements in the loop.
    Listing 18-2 shows a countdown like the one from Chapter 17 , but using a while loop.
    Listing 18-2 Count Down with while
    var count = 10; while (count > 0) {   alert(count);   count--; } alert("Blast Off!");

    Looping through an array with while

    Looping through arrays with while is easier than it is with for . To loop through an array with while
  • The JavaScript Workshop
    eBook - ePub

    The JavaScript Workshop

    A New, Interactive Approach to Learning JavaScript

    • Joseph Labrecque, Jahred Love, Daniel Rosenbaum, Nick Turner, Gaurav Mehla, Alonzo L. Hosford, Florian Sloot, Philip Kirkbride(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    1 . After the loop, the matched value and the iterations are displayed.
  • Run a few tests by reloading the do-while-statements.html web page in your web browser with the console window open. Your results will differ due to the random values.The following example is the result of more than one iteration: Die 1: 1 Die 2: 3 Die 1: 2 Die 2: 3 Die 1: 5 Die 2: 4 Die 1: 3 Die 2: 1 Die 1: 4 Die 2: 4  The matched value is:  4 Number of iterations:  5 The following example is the result of a single iteration: Die 1: 4 Die 2: 4 The matched value is:  4 Number of iterations:  1
  • while Statement

    The while statement is a loop that executes code if the repeat expression is true/false . The repeat expression is evaluated before any code is executed, so there is the possibility that no code is processed if it is false the first time round. The syntax is as follows:
    while(repeat expression){    //Statement    //Statement } while (repeat expression)    //Single statement
    The while statement flow is illustrated as follows:
    Figure 3.12: Code statements in the while block

    Exercise 3.11: Writing a while Loop and Testing It

    In this exercise, we will use the while loop to simulate how many dice rolls it takes to roll an even number. Let's get started:
    1. Open the while-statement.html document in your web browser.
    2. Open the web developer console window using your web browser.
    3. Open the while-statement.js document in your code editor, replace all of its content with the following code, and then save it:let iterations = 0; while (iterations <10){  console.log("iterations:", iterations);  iterations ++; }
      This is just the initial shell for a while loop that repeats 10 times. The while loop's repeat expression is true if the iterations variable is below the value of 10 . The first time the expression is evaluated, the iterations variable is 0 . Inside the while loop, the iterations variable is incremented by 1 on the first line and will increase from 0 to 9
  • 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
  • Clean Code in JavaScript
    eBook - ePub

    Clean Code in JavaScript

    Develop reliable, maintainable, and robust JavaScript

    for...of. Nonetheless, it is useful to know how to cleanly wield it.
    Passage contains an image

    The do...while statement

    The do...while statement is similar to while it although guarantees an iteration before the check is carried out. Its syntax is formed of the do keyword followed by its body and then a typical parenthesized while expression:
    do IterationBody while (ConditionExpression) The purpose of each part is as follows:
    • IterationBody can be either a single-line or block statement and will be run once initially and then as many times as ConditionExpression evaluates to true.
    • ConditionExpression is evaluated to determine whether IterationBody should run more than once. If it evaluates to true, then the Body portion will run. ConditionExpression will then be re-evaluated and so on. The cycle only stops when ConditionExpression evaluates to false.
    Although the behavior of the do...while statement is different from regular while statement, its semantics and broad applications remain the same. It is most useful in contexts where you need to always complete at least one step of an iteration before either checking whether to continue or changing the subject of the iteration. An example of this would be upward DOM traversal. If you have a DOM element and wish to run certain code on it and each of its DOM ancestors, then you may wish to use a do...while statement as follows:
    do { // Do something with `element`} while (element = element.parentNode);
    A loop like this will execute its body once for the element value, whatever element is, and then will evaluate the assignment expression, element = element.parentNode. This assignment expression will evaluate to its newly assigned value, meaning that, in the case of element.parentNode being falsy (for example, null) the do...while
  • Learn C Programming
    Very often, we need to perform a series of statements repeatedly. We might want to perform a calculation on each member of a set of values, or we might want to perform a calculation using all of the members in a set of values. Given a collection of values, we also might want to iterate over the whole collection to find the desired value, to count all the values, to perform some kind of calculation on them, or to manipulate the set in some way – say, to sort it.
    There are a number of ways to do this. The simplest, yet most restrictive way is the brute-force method . This can be done regardless of the language being used. A more dynamic and flexible method is to iterate or repeatedly loop. C provides three interrelated looping statements – while()… , for()… , and do … while() . Each of them has a control or continuation expression, and a loop body. The most general form of these is the while()… loop. Lastly, there is the archaic goto label method of looping. Unlike other languages, there is no repeat … until() statement; such a statement can easily be constructed from any of the others.
    Each looping statement consists of the following two basic parts:
    • The loop continuation expression
    • The body of the loop
    When the loop continuation expression evaluates to true , the body of the loop is executed. The execution then returns to the continuation expression, evaluates it, and, if true , the body of the loop is again executed. This cycle repeats until the continuation expression evaluates to false ; the loop ends, and the execution commences after the end of the loop body.
    There are two general types of continuation expressions used for looping statements, as follows:
    • Counter-controlled looping , where the number of iterations is dependent upon a count of some kind. The desired number of iterations is known beforehand. The counter may be increasing or decreasing.
    • Condition- or sentinel-controlled looping
  • 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.