When this code block runs, what happens logically step by step or how is the result evaluated?

Viewed 34

I tried to run the following Node.js code:

for (let a = 5; a === 11 ; a++) {
  console.log(a);
  }

I want to know how this loop returns the result . (Logically, step by step.) Why does it log nothing to the console?

Example:

  • It starts with 5.
  • It then gets added by 1 each time.
  • It's stopping condition is...

Thanks in advance and do ask in comments if the question wasn't clear.

2 Answers

This particular loop should not print anything.

for (let a = 5; a === 11 ; a++) {
  console.log(a);
  }

The loop states: "Execute the code inside me, as long as a is equal to 11. However, in our case, a is initialized to 5. Because of this, when we first start the loop, its run condition is already false, so it never executes.

An example of a loop that would print the numbers from 5 to 10:

for (let a = 5; a < 11 ; a++) {
  console.log(a);
}

It is important to note that the condition in a for loop is the run condition, not the end condition.

Ok, so your problem here is that it only runs if the variable A is equal to 11. If you want everything from 5 below 11 you use a < symbol.

I'll explain the steps in this example.

for (a = 5; a < 11; a++) {
    console.log(a)
}

  1. It starts with 5.
  2. It then gets added by 1 each time.
  3. Its stopping condition is if A is greater than or equal to 11.
Related