Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this for loop print 6 and 10?

I am learning JS and I stumbled across this. I don’t understand why it prints 6 and 10.
Could someone please explain the steps and why I am getting these numbers?

var apple = 1;
for (var apple = 0; apple < 10; apple = apple + 2) {
    
    orange = orange + 1;
}
console.log(orange);
console.log(apple);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First of all the code you provided will throw errors. I am assuming it is:

var orange = 1;
for (var apple = 0; apple < 10; apple = apple + 2) {
    
    orange = orange + 1;
}
console.log(orange);
console.log(apple);

Here the for loop will run 5 times:

  1. apple = 0 orange = 1
  2. apple = 2 orange = 2
  3. apple = 4 orange = 3
  4. apple = 6 orange = 4
  5. apple = 8 orange = 5
  6. apple = 10 orange = 6

The 6th time it will break as apple = 10 which is not < 10. So the final values are 6 and 10.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading