Loops: while and for

We often need to do something repeatedly.

For example, we need to print the items in the list one by one, or run the same code to print the numbers 1 through 10 one by one.

A loop is a way to run the same code repeatedly.

“While” loop

The syntax for the while loop is as follows:

while (condition) {
  / / code
  // The so-called "circulation body"
}
Copy the code

When condition is true, the loop body’s code is executed.

For example, the following loop outputs the value of I when I < 3:

let i = 0;
while (i < 3) { // Display 0, 1, and 2 in sequence
  alert( i );
  i++;
}
Copy the code

A single execution of the loop body is called an iteration. The loop in the example above has three iterations.

Without i++ in the example above, the loop would (in theory) repeat forever. In fact, browsers provide a way to stop this loop by stopping the JavaScript on the server side by terminating the process.

Any expression or variable can be a cyclic condition, not just a comparison. The loop condition in the while is evaluated and the result is converted to a Boolean value.

For example, while (I! = 0) while (I) :

let i = 3;

while (i) { // When I becomes 0, the condition is false and the loop terminates
  alert( i );
  i--;
}
Copy the code

Single-line loop bodies do not need braces:

If the body of the loop has only one statement, the braces {… } :

let i = 3;

while (i) alert(i--);
Copy the code

“do.. The while loop”

Using the do.. The while syntax moves the condition check below the body of the loop:

do {
  / / the loop body
} while (condition);
Copy the code

The loop first executes the body of the loop, then checks the condition, and when the condition is true, executes the body repeatedly.

Such as:

let i = 0;
do {
  alert( i );
  i++;
} while (i < 3);
Copy the code

This form of syntax is rarely used unless you want the body of the loop to be executed at least once, regardless of whether the condition is true. Usually we prefer to use another form: while(…) {… }.

“For” loop

The for loop is more complex, but it is the most commonly used form of loop.

The for loop looks something like this:

for (begin; condition; step) {
  / /... The loop body...
}
Copy the code

Let’s use examples to see what these three parts mean. The following loop runs alert(I) from I equals 0 to 3 (but not 3) :

for (let i = 0; i < 3; i++) { // The result is 0, 1, 2
  alert(i);
}
Copy the code

Let’s analyze the for loop piece by piece:

Statement period
begin i = 0 Execute once upon entering the loop.
condition i < 3 Check before each iteration of the loop and, if false, stop the loop.
Body (circulatory body) alert(i) If the condition is true, repeat the run.
step i++ Executes after each iteration of the loop body.

The working principle of the general loop algorithm is as follows:

Start running → (if condition is true → Run body and then run step) → (if condition is true → run body and then run step) → (If condition is true → Run body and then run step Step) - >...Copy the code

So begin executes once, and then iterates: After each condition check, body and step are executed.

If this is your first experience with loops, it might be helpful to go back to this example and recreate the step-by-step process on a piece of paper.

Here’s what happens in this example:

// for (let i = 0; i < 3; i++) alert(i)

/ /
let i = 0
If the condition is true, run the next step
if (i < 3) { alert(i); i++ }
If the condition is true, run the next step
if (i < 3) { alert(i); i++ }
If the condition is true, run the next step
if (i < 3) { alert(i); i++ }
/ /... I'm done, because now I == 3
Copy the code

Inline variable declarations

Here the “count” variable I is declared in the loop. This is called an “inline” variable declaration. Such variables are only visible in the loop.

for (let i = 0; i < 3; i++) {
  alert(i); / / 0, 1, 2
}
alert(i); // Error, there is no such variable.
Copy the code

Instead of defining a variable, we can also use an existing variable:

let i = 0;

for (i = 0; i < 3; i++) { // Use existing variables
  alert(i); / / 0, 1, 2
}

alert(i); //3, visible because it is declared outside the loop
Copy the code

Omitting statement segment

Any section of the for loop can be omitted.

For example, if we don’t need to do anything at the beginning of the loop, we can omit the begin statement segment.

Something like this:

let i = 0; // We have declared I and assigned it a value

for (; i < 3; i++) { // The "begin" statement is no longer required
  alert( i ); / / 0, 1, 2
}
Copy the code

We can also remove the step statement segment:

let i = 0;

for (; i < 3;) {
  alert( i++ );
}
Copy the code

This loop is equivalent to while (I < 3).

We can actually delete everything to create an infinite loop:

for (;;) {
  // Infinite loop
}
Copy the code

Notice the two for; Must exist, otherwise syntax errors will occur.

Jump out of the loop

Normally when the condition is false, the loop terminates.

But we can always use the break command to force an exit.

For example, the following loop asks the user to enter a series of numbers and “terminates” the loop when the input is not a number.

let sum = 0;

while (true) {
  let value = +prompt("Enter a number".' ');
  if(! value)break; / / (*)
  sum += value;
}
alert( 'Sum: ' + sum );
Copy the code

If the user enters a blank line or cancels typing, the break instruction on line (*) is activated. It immediately terminates the loop, passing control to the first line after the loop, alert.

As needed, the combination of “infinite loop + break” is ideal for situations where conditions are not checked at the beginning/end of the loop, but need to be checked at multiple locations in the middle or even in the body.

Continue to the next iteration

The continue directive is a “lighter version” of break. It doesn’t stop the whole cycle. Instead, stop the current iteration and force a new cycle (if possible).

We can use it if we have completed the current iteration and want to move on to the next one.

The following loop uses continue to print only odd numbers:

for (let i = 0; i < 10; i++) {
  // If true, skip the rest of the loop body.
  if (i % 2= =0) continue;
  alert(i); // 1, then 3,5,7,9
}
Copy the code

For an even number of I values, the continue instruction stops the continuation of the loop, passing control to the next iteration of the for loop (using the next number). So alert is called only by odd values.


The continue directive helps reduce nesting:

A loop that displays odd numbers could look like this:

for (let i = 0; i < 10; i++) {
  if (i % 2) { alert( i ); }}Copy the code

From a technical point of view, it is exactly the same as the previous example. Of course, we can wrap code in an if block instead of using continue.

But in terms of side effects, it creates one more layer of nesting (alert calls in curly braces). If there are more than one line of code in the if, it may reduce the overall readability of the code.


Note: Nobreak/continueIn the ‘? ‘on the right side of the

Note that non-expression syntactic structures cannot be associated with ternary operators? Use together. In particular, directives such as break/continue are not allowed to be used this way.

For example, we use the following code:

if (i > 5) {
  alert(i);
} else {
  continue;
}
Copy the code

… Rewrite with a question mark:

(i > 5)? alert(i) :continue; // continue is not allowed at this position
Copy the code

… The code stops running and displays a syntax error.

Is it just not used? Not another reason for if.


Break/continue

Sometimes we need to break out of multiple nested loops at once.

For example, in the following code our loop uses I and j to indicate coordinates (I, j) from (0,0) to (3,3) :

for (let i = 0; i < 3; i++) {

  for (let j = 0; j < 3; j++) {

    let input = prompt(`Value at coords (${i}.${j}) `.' ');

    // If I want to exit from here and execute alert('Done! ')
  }
}

alert('Done! ');
Copy the code

We need to provide a way to stop this process when the user cancels input.

A normal break after the input only breaks the inner loop. That’s not enough — tags do it!

A label is an identifier preceded by a colon:

labelName: for (...) {
  ...
}
Copy the code

The break

statement breaks the loop to the tag:

outer: for (let i = 0; i < 3; i++) {

  for (let j = 0; j < 3; j++) {

    let input = prompt(`Value at coords (${i}.${j}) `.' ');

    // If the string is empty or cancelled, break out of both loops.
    if(! input)break outer; / / (*)

    // Do something with the value...
  }
}
alert('Done! ');
Copy the code

In the code above, break outer looks up for the tag named OUTER and jumps out of the current loop.

Therefore, control is transferred directly from (*) to alert(‘Done! ‘).

We can also move the label to a single line:

outer:
for (let i = 0; i < 3; i++) { ... }
Copy the code

The continue directive can also be used with labels. In this case, the jump to the next iteration of the marker loop is performed.


Note: Tags are not allowed to “jump” to all locations

The tag does not allow us to jump anywhere in the code.

For example, it would be impossible to do so:

break label;  // Cannot jump to this tag

label: for(...).Copy the code

Break /continue can only be called inside the loop, and the label must be somewhere above the directive.


conclusion

We learned three cycles:

  • whileCheck conditions before each iteration.
  • do.. while— Check conditions after each iteration.
  • for (;;)Conditions are checked before each iteration, and other Settings can be used.

While (true) is usually used to construct “infinite” loops. This loop, like any other loop, can be terminated with the break command.

If we don’t want to do anything in the current iteration and want to move on to the next iteration, we can use the continue directive.

Break /continue supports labels before loops. The tag is the only way to break/continue out of the nested loop to go outside.

Homework assignments

Do the questions yourself and then look at the answers.

1. Value of the last loop

Importance: ⭐️⭐️ ️

What was the last alert value of this code? Why is that?

let i = 3;

while (i) {
  alert( i-- );
}
Copy the code

2. What values are displayed in the while loop?

Degree of importance: ⭐️⭐️ ️⭐

For each loop, write down the value you think will be displayed and compare it to the answer.

Do the following two loops have the same alert value?

  1. Prefix form ++ I:

    let i = 0;
    while (++i < 5) alert( i );
    Copy the code
  2. Suffix i++

    let i = 0;
    while (i++ < 5) alert( i );
    Copy the code

3. What values are displayed in the “for” loop?

Degree of importance: ⭐️⭐️ ️⭐

For each loop, write down the value it will display. Then compare them with the answers.

Is the alert value the same for both loops?

  1. Suffix form:

    for (let i = 0; i < 5; i++) alert( i );
    Copy the code
  2. Prefix form:

    for (let i = 0; i < 5; ++i) alert( i );
    Copy the code

4. Use the for loop to print even numbers

Importance: ⭐️⭐ ⭐️⭐️

Use the for loop to print even numbers from 2 to 10.

5. Replace “for” with “while”

Importance: ⭐️⭐ ⭐️⭐️

Rewrite the code to change the for loop to while (the output should remain the same) without changing its behavior.

for (let i = 0; i < 3; i++) {
  alert( `number ${i}! ` );
}
Copy the code

6. Repeat the input until the information is correct

Importance: ⭐️⭐ ⭐️⭐️

Write a loop that prompts the user to enter a number greater than 100. If the user enters another value — ask him to re-enter it.

The loop keeps asking for a number until the user enters a number greater than 100, cancels the input, or enters a null action.

We’re going to assume that the user is only going to enter numbers. In this case, no special treatment is required for non-numeric inputs.

7. Output prime

Importance: ⭐️⭐️ ️

Integers greater than 1 and not divisible by any number other than 1 and itself are called prime numbers.

In other words, integers whose n is greater than 1 and cannot be divisible by any number other than 1 and n are called prime numbers.

For example, 5 is prime because it is not divisible by 2, 3, and 4, resulting in a remainder.

Write one that can output2nCode between all prime numbers.

When n = 10, the result outputs 2, 3, 5, 7.

The P.S. code should be applied to any N, not hard-wired to any fixed value.

The answer:

Reply 1-2-12 in the background of wechat public account “Technology Chat” to obtain the answer to this question.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Scan the QR code below and follow the wechat public account “Technology Chat” to subscribe for more exciting content.