How Do I Run a While Loop Again After I Break It
Loops and Iterating
Most programs require code that runs over and over until some catastrophe status occurs. Most programming languages, including JavaScript, employ loops to provide this capability. JavaScript loops have several forms, merely the master looping structures use a looping keyword, a condition, and a block. These loops execute the loop'southward body (the cake) for as long as the condition remains truthy. Nosotros use the term ane iteration to describe executing the loop trunk one time. JavaScript also has two other loop mechanisms: array abstractions and recursion. We'll see all of these mechanisms in this affiliate.
Permit'south start with the while loop.
while Loops
A while loop uses the while keyword followed past a conditional expression in parentheses and a cake. The loop executes the block again and once again for as long as the conditional expression remains truthy. In about programs, that loop should ultimately end repeating. That means that the block must do something that tells JavaScript when the loop should stop; that is, it needs to suit for the conditional expression to go falsy. Otherwise, the loop is an space loop that never stops repeating.
To come across why a while loop is useful, consider writing some code that logs numbers from 1 to 10:
panel.log(one); panel.log(2); console.log(three); console.log(4); panel.log(five); console.log(6); console.log(seven); console.log(8); console.log(9); console.log(10); While that code is straightforward and readily understood, it'south easy to see that this approach isn't sustainable. Suppose we demand to log numbers from 1 to 1000 or i,000,000. If you had to write all that code for such a unproblematic task, you would presently come to regret your career choice.
Let's rewrite the plan with a while loop. Create a file named counter.js with the following lawmaking and run it:
let counter = i; while (counter <= x) { panel.log(counter); counter = counter + 1; } This code does the same thing equally the first program, but more than programmatically. If you want to log 1000 numbers or even a one thousand thousand, all you have to change is the conditional expression:
allow counter = 1; #highlight while (counter <= 1000) {
0 Response to "How Do I Run a While Loop Again After I Break It"
Post a Comment