New course! Every coder should learn Generative AI!
Try a free lesson+ 6
The first program outputs 1 and the second outputs 24, what could have been the reason behind such results?
//First program var x = 1; for(var i = 0; i < 10; i++) { for(var j = 0; j >= 2; j++) { for(var k = 0; k < 5; k++) { x++; } } } document.write(x); //Second program var a = "1"; var b = "2*2" console.log(eval(a+b));
5 Answers
+ 4
Just think about it. I will just remove the code that doesn't run:
for (var i = 0; i < 10; i++) {
for (var j = 0; j >= 2; j++) {
for (var k = 0; k < 5; k++) {
x++
}
}
}
Then removed:
for (var i = 0; i < 10; i++) {
//for (var j = 0; j >= 2; j++) {
//for (var k = 0; k < 5; k++) {
//x++;
//}
//}
}
To:
for (var i = 0; i < 10; i++) {
}
+ 4
First:
The second loop never executes. If you look at it closely, it's j >= 2, and that will never be true.
Second:
The inputs are added before being evaluated (you know, like with parentheses). "1" + "2 * 2" is "12 * 2), and that's evaluated to 24
+ 4
Airree, I've got to say a big thank you to you because you're really helping learn me something new every day
+ 4
Third loop and x++ are statements inside second loop and when it will never run, they won't run too. So "x" remains 1.
+ 2
Your explanation for the first program is not complete. Due to the fact that the second loop is false, Airree, are you now saying that that means iteration won't occur because one of the loop is false?