Computer Science

Javascript Do While Loop

The JavaScript do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block of code as long as the specified condition is true. It is similar to the while loop, but the block of code is executed before the condition is checked.

Written by Perlego with AI-assistance

5 Key excerpts on "Javascript Do While Loop"

  • Jump Start JavaScript
    eBook - ePub

    Jump Start JavaScript

    Get Up to Speed With JavaScript in a Weekend

    • Ara Pehlivanian, Don Nguyen(Authors)
    • 2013(Publication Date)
    • SitePoint
      (Publisher)
    this excellent article written by our technical editor, Colin Ihrig.
    The while loop can be illustrated with this simple example:
    var tasksToDo = 3; while (tasksToDo > 0) { console.log('There are ' + tasksToDo + ' tasks to do'); tasksToDo--; } This prints the following to the console: There are 3 tasks to do There are 2 tasks to do There are 1 tasks to do
    When using a while loop, it’s important to make sure that the condition eventually evaluates to false . During each iteration of the loop, some variable should be changing that will eventually lead to the condition being false , thereby terminating the loop. Otherwise, your program becomes stuck in the dreaded infinite loop. For an example of a subtle bug that leads to an infinite loop, consider this:
    function getNext(num) { return num++; } var i=0; while (i < 3) { i = getNext(i); }
    At first it may be hard to even spot the bug. Note that num++ will return the value of num , and then increment the value. Therefore, in the while loop, the value of i will always be zero! Whenever you are writing a while loop, always double-check that the loop will gracefully exit. With patience and practice this will soon become second nature.

    The do ... while Loop

    The do ... while loop is a variation of the while loop that takes the following form:
    do { statement } while(expression);
    The main difference between the two is that execution is guaranteed at least once with the do ... 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
  • 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
  • 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
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.