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 :
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:
apple = 0orange = 1apple = 2orange = 2apple = 4orange = 3apple = 6orange = 4apple = 8orange = 5apple = 10orange = 6
The 6th time it will break as apple = 10 which is not < 10. So the final values are 6 and 10.