Why is this code different?

console.log('i am using while loop')
let i=0;
while(i<10){
   i++;
   console.log(i);
}


//Inside

let j=0;
while(j<10){
   console.log(j);
    j++;
}

Hi,

The key difference is where the β€˜++’ is located.
The first while loop prints the numbers 1-10 whereas the second loop prints the numbers 0-9.

You might be aware that in JavaScript (and also other languages) ++ denotes add 1 to a variable.

let i=0;
while(i<10){
   i++;
   console.log(i);
}

The first loop starts by setting i to 0. Then, JavaScript is told to run the loop until i is less than 10.
However, the variable is incremented by 1 before we are told the contents of i. For example:

  1. i is set to 0.
  2. Is i is less than (<) 10? Yes, so run the code within the loop.
  3. Add 1 to i which is 1.
  4. Output i which gives a result of 1.

This is repeated for as long as i is less than 10.
You may be wondering why we then get a result of 10 from this loop because 10 is not less than 10.
It’s because at the start of the loop, i = 9. It’s just that 1 is added before we are told what i is.

The second loop has the ++ after the console.log() statement. This means that the output is shifted to the left by 1.

let j=0;
while(j<10){
   console.log(j);
    j++;
}

For example:

  1. j is set to 0.
  2. Is j less than (<) 10? Yes, so run the code within the loop.
  3. Output the value of j which is 0.
  4. Add 1 to j (so it becomes 1).

This is repeated until j is less than 10.
Note that we never get to a value of 10 because on the last iteration the variable j is set to 10.
Therefore, as 10 is not less than 10, the code stops.

I hope that helps!

2 Likes