“Loops” memo. Part 1

Loop for

Syntax

for (var i = 0; i < 10; i++) {
  // repeated commands
}

var i = 0; preparatory part, the initial value for the counter. Set with var, as an ordinary variable.

i < 10; checking part. If the condition returns true, the loop completes one more iteration, otherwise the loop stops.

i++ complementary part, launched at each iteration, after executing the code from the body of the loop. Changes counter value.

Accumulation of values ​​in a loop:

var sum = 0;

for (var i = 1; i <= 5; i++) {
  sum += 2;
  console.log(sum);
}

The program will log:

LOG: 2 (number)
LOG: 4 (number)
LOG: 6 (number)
LOG: 8 (number)
LOG: 10 (number)

Checks in the loop body

var sum = 0;

for (var i = 1; i <= 5; i++) {
  if (i > 2) {
    sum += 1;
  }
}

Searching for an even number

The % operator or the “remainder in division” returns the remainder in division.

10 % 5;  // Returns 0
12 % 5;  // Returns 2
7 % 3;   // Returns 1
5.5 % 2; // Returns 1.5

If the remainder in division of the number by 2 equals 0, the number is even, otherwise it is odd.


Continue

We are using cookies to gather information which will help you use our website most effectively. You can read about this here or disable this feature if you want. By continuing to browse the site, you agree to our use of cookies.