Javascript Function Run Again if Condition Is Not Met
Loops and Iterating
About programs require code that runs over and over until some catastrophe status occurs. Near programming languages, including JavaScript, use loops to provide this adequacy. JavaScript loops take several forms, but the master looping structures employ a looping keyword, a condition, and a block. These loops execute the loop's body (the block) for as long as the status remains truthy. Nosotros use the term i iteration to describe executing the loop torso once. JavaScript besides has two other loop mechanisms: assortment abstractions and recursion. Nosotros'll see all of these mechanisms in this affiliate.
Allow'due south kickoff with the while loop.
while Loops
A while loop uses the while keyword followed by a conditional expression in parentheses and a cake. The loop executes the block again and over 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 practice something that tells JavaScript when the loop should stop; that is, it needs to arrange for the conditional expression to go falsy. Otherwise, the loop is an infinite loop that never stops repeating.
To see why a while loop is useful, consider writing some code that logs numbers from one to 10:
panel.log(1); console.log(2); console.log(3); console.log(4); console.log(5); console.log(half-dozen); console.log(vii); console.log(8); console.log(9); panel.log(10); While that code is straightforward and readily understood, information technology'southward piece of cake to see that this arroyo isn't sustainable. Suppose we need to log numbers from one to thou or 1,000,000. If you had to write all that lawmaking for such a uncomplicated task, y'all would soon come to regret your career choice.
Permit's rewrite the program with a while loop. Create a file named counter.js with the following lawmaking and run it:
let counter = 1; while (counter <= 10) { console.log(counter); counter = counter + i; } This code does the aforementioned thing as the showtime program, but more programmatically. If you want to log yard numbers or even a meg, all you have to change is the conditional expression:
let counter = ane; #highlight while (counter <= 1000) {
0 Response to "Javascript Function Run Again if Condition Is Not Met"
Post a Comment