Summary of “Loops”. Part 1

The for loop

Syntax

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

var i = 0; — initialization: declares the counter with var and sets its initial value.

i < 10; — condition: checked before each iteration. If it is true, the loop runs another iteration; otherwise, it stops.

i++ — update: runs after the loop body on each iteration and increases the counter by one.

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, called the remainder operator, returns the amount left over after division.

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

If an integer divided by 2 has a remainder of 0, it is even; otherwise, it is odd.


Continue