There are corresponding pre-decrement and post-decrement operators (e.g., -a and a-) that work in a similar way. JavaScript has an even more succinct syntax to increment a number by 1. Create a file named counter.js with the following code and run it: let counter = 1 Let's rewrite the program with a while loop. If you had to write all that code for such a simple task, you would soon come to regret your career choice. Suppose we need to log numbers from 1 to 1000 or 1,000,000. While that code is straightforward and readily understood, it's easy to see that this approach isn't sustainable. To see why a while loop is useful, consider writing some code that logs numbers from 1 to 10: console.log(1) Otherwise, the loop is an infinite loop that never stops repeating. That means that the block must do something that tells JavaScript when the loop should stop that is, it needs to arrange for the conditional expression to become falsy. In most programs, that loop should ultimately stop repeating. The loop executes the block again and again for as long as the conditional expression remains truthy. while LoopsĪ while loop uses the while keyword followed by a conditional expression in parentheses and a block. We'll see all of these mechanisms in this chapter. JavaScript also has two other loop mechanisms: array abstractions and recursion. We use the term one iteration to describe executing the loop body once. These loops execute the loop's body (the block) for as long as the condition remains truthy. JavaScript loops have several forms, but the main looping structures use a looping keyword, a condition, and a block. Most programming languages, including JavaScript, use loops to provide this capability. Most programs require code that runs over and over until some ending condition occurs.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |