I hope YOU guys are doing good I am learning Javascript I got to know about "continue" which we can use in loop for iteration. But here is what i can't get
First have a look at the code:
let k = 1
do {
if (k === 9) {
k++;
continue;
}
console.log(k + 1);
k++;
} while (k < 15);
When in console.log is (k+1)then, 9 is printed and 10 is missed. Can't get why?
But when this code is used
let k = 1
do {
if (k === 9) {
k++;
continue;
}
console.log(k);
k++;
} while (k < 15);
When in console.log is (k)then, 9 is not printed and 10 is printed.
Can't understand the logic behind when simple (k) is used and when (k+1) is used?
So this is what i understood is. That if K=1. console.log(k+1). 2 is printed. and then due to k++. k becomes 2 and condition is tested and as it is true so it will move to another loop. And this continues. Right?
Thanks
continue skips the rest of the loop body and starts the next iteration of the loop (if the while condition is still true).
In both code snippets, you do this when k == 9, so it skips over the code that calls console.log().
In the first version, it logs k+1. So when k == 9 it skips printing 10.
In the second version, it logs k. So when k == 9 it skips printing 9.
That is because in your logic, if k === 9, you add +1 to k and then log it to console, which makes 9 invisible. You should log it and then add k++.
In the first example, you're logging the value of k+1 so, when k is 1 it logs the value 2 (1+1), when k is 2 it logs the value 3 (2+1) all the way up to where k is 8 and logs 9 (8+1). When k is 9 though, k is still incremented and k+1 is 10 but this doesn't get logged because the rest of the loop is skipped.
In the second example, you're doing exactly the same thing but loggin the value of k not k+1 so all the logged values are 1 less.
"...can YOU also explain k++ under console.log(k+1)"
In both cases the value of k is incremented by 1 each time around the loops either at the end of the block, after the console.log or inside the if (k === 9) block before continue