Home > database >  How does the for loop operate exactly?
How does the for loop operate exactly?

Time:04-08

for (let counter = 3; counter >= 0 ; counter--){
  console.log(counter);
}

I am still learning and I am making a simple for loop that logs the numbers 3 2 1 0 and I am having a difficulty understanding why do I have to set the stopping condition (counter >= 0) which comes after the initialization ( let counter = 3) and not ( counter > 0 ) to get the right answer. isn’t the number 1 is bigger than 0 and when checked against the stopping condition should evaluate to true? also why when I set the stopping condition to counter = 0 it doesn't log anything?

CodePudding user response:

A for loop in the form

for (initialization; condition; increment) {
    body
}

is roughly* equivalent to the while loop:

initialization;
while (condition) {
    body;
    increment;
}

If you change the condition to counter == 0 (I'm assuming = was a typo in the question, not the actual code), the while condition fails the first time, because 3 == 0 is not true. So the body is never executed and the loop stops immediately.

[*] I say "roughly" because there's a difference related to variable scope if let is used to declare the variable in the initialization clause.

CodePudding user response:

Let's break down your code:

for (let counter = 3; counter >= 0 ; counter--){
  console.log(counter);
}

We need a initiator for starting a loop. So we started with counter from 3. Then we gave it an iteration condition that if counter is less than or equals zero the loop will iterate and on each move it will decrease the counter number by one. The (--) means decrement. Now come to your problem. (>=) will continue the loop on 0 and only using (>) will stop it before zero. This is the difference. You can change it and see what happens. counter = 0 you can't set a condition like this. A condition must have two operators eg. (==)(!=)(>=)(<=). So the use is invalid. We use this format to declare a new value into variable.

CodePudding user response:

Breaking it down into three parts:
First part: counter=3
Second part: counter>=0
Third part: counter--

For the first part:
It is the initialisation, which sets the variable counter to 3.

For the second part:
It is the condition. It will stop the loop when the condition is false.
The condition consists of an operator.
For the operator, >= means bigger than or equal. == means equal
Note that = isn't a comparison operator. It means 'counter is 0'.

For the third part:
It is the operation.
It will run every iteration, or cycle.
-- means 'decrease by 1'

  • Related