What if We Define the Variable Again Inside the Loop

Loops and Iterating

Most programs crave lawmaking that runs over and over until some catastrophe condition occurs. Nigh programming languages, including JavaScript, use loops to provide this capability. JavaScript loops have several forms, but the master looping structures use 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. We use the term one iteration to describe executing the loop body once. JavaScript also has 2 other loop mechanisms: array abstractions and recursion. We'll see all of these mechanisms in this chapter.

Let'southward outset 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 block again and again for as long as the conditional expression remains truthy. In most programs, that loop should ultimately stop 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. 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 1 to ten:

          panel.log(one); panel.log(2); panel.log(3); console.log(4); console.log(5); console.log(6); console.log(vii); console.log(eight); console.log(nine); console.log(10);                  

While that code is straightforward and readily understood, it's easy to see that this approach isn't sustainable. Suppose we need to log numbers from one to 1000 or i,000,000. If you had to write all that code for such a simple job, you lot would soon come to regret your career choice.

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

          permit counter = 1; while (counter <= 10) {   panel.log(counter);   counter = counter + 1; }                  

This code does the same thing as the first program, only more programmatically. If yous desire to log m numbers or fifty-fifty a 1000000, all you have to change is the conditional expression:

          allow counter = 1; #highlight while (counter <= 1000) { 

0 Response to "What if We Define the Variable Again Inside the Loop"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel