For Loop How to Use Variable Again

Loops and Iterating

About programs crave code that runs over and over until some ending condition occurs. Most programming languages, including JavaScript, utilize loops to provide this capability. JavaScript loops accept several forms, merely the primary looping structures utilize a looping keyword, a condition, and a block. These loops execute the loop's trunk (the block) for every bit long equally the condition remains truthy. We use the term i iteration to describe executing the loop torso once. JavaScript likewise has ii other loop mechanisms: array abstractions and recursion. We'll see all of these mechanisms in this affiliate.

Allow's start with the while loop.

while Loops

A while loop uses the while keyword followed by a conditional expression in parentheses and a block. The loop executes the cake again and again for every bit long as the conditional expression remains truthy. In virtually programs, that loop should ultimately stop repeating. That ways that the cake must do something that tells JavaScript when the loop should stop; that is, it needs to arrange for the provisional expression to get falsy. Otherwise, the loop is an infinite loop that never stops repeating.

To see why a while loop is useful, consider writing some lawmaking that logs numbers from 1 to 10:

          console.log(1); console.log(two); console.log(3); console.log(iv); console.log(five); console.log(6); console.log(7); console.log(8); console.log(nine); console.log(10);                  

While that code is straightforward and readily understood, it'southward easy to see that this approach isn't sustainable. Suppose nosotros need to log numbers from 1 to thou or 1,000,000. If yous had to write all that lawmaking for such a unproblematic chore, you would soon come to regret your career selection.

Let'due south rewrite the program with a while loop. Create a file named counter.js with the following code and run it:

          let counter = 1; while (counter <= ten) {   panel.log(counter);   counter = counter + 1; }                  

This code does the same thing equally the first program, but more programmatically. If you desire to log yard numbers or even a million, all you have to change is the conditional expression:

          allow counter = ane; #highlight while (counter <= thousand) { 

0 Response to "For Loop How to Use Variable Again"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel