Javascript Loop Question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Javascript Loop Question

One of the Javascript quiz questions was as following: Will this code create an infinite loop? × Yes × No var y = 1; while(y > 0) { y++; }; I said 'no' because a positive numbered variable is not infinitely long and has a numeral limit right? Apparently the correct answer is 'yes', but somehow I find this hard to believe. Can a experienced programmer explain to me if I am wrong or right? Thank you.

6th Jan 2017, 2:38 PM
John van den Elzen
John van den Elzen - avatar
8 Answers
+ 2
but isn't that the whole point? If I would run this code on any machine it would eventually stop working and thus the loop is never infinite in real life. It would just be bad practice.
6th Jan 2017, 2:52 PM
John van den Elzen
John van den Elzen - avatar
+ 2
+/- 9007199254740991 is the highest var number. Not quite sure what happens after this. But so far, you are right. It isn't a infinite loop.
6th Jan 2017, 2:57 PM
Jonas Fallmann
Jonas Fallmann - avatar
+ 1
well, you are right. After some time the RAM will be full or the limit of a JS var will be reached and the Programm crashes. But as there is no given limit in the question, the answer should be "YES".
6th Jan 2017, 2:50 PM
Jonas Fallmann
Jonas Fallmann - avatar
+ 1
If you got infinite RAM you are good to go
6th Jan 2017, 2:53 PM
Jonas Fallmann
Jonas Fallmann - avatar
+ 1
nobody has infinite ram? and isnt a variable numeral type like int, double, float, long etc. always capped?
6th Jan 2017, 2:56 PM
John van den Elzen
John van den Elzen - avatar
+ 1
@Ian : All loops repeat until their condition is false. The do... while () loop however is always executed once (before the condition is checked). Also, OP, you're right. The loop will be faulty.
6th Jan 2017, 4:16 PM
Nsyse
Nsyse - avatar
0
the answer is no if the loop was for or do any they would do there own code over and over again untill the statements are true, but with while the while statement will repeat itself untill the statements are not true so basically while will repeat itself when the statements are true var y = 1; while(y > 0) { y++; };
6th Jan 2017, 2:57 PM
Ian
Ian - avatar
0
exactly @Jonas Fallmann ... and if that maximum value of the datatype is reached it wraps I believe... starting at the lowest value possible... which in that case is the negative equilevant of the maximum value and thus the value will be less than 0. I believe this is what happens and therefore I want to know for sure because I truely believe the quiz questions set answer is dead wrong.
6th Jan 2017, 3:00 PM
John van den Elzen
John van den Elzen - avatar