why would this JavaScript code block return 5? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

why would this JavaScript code block return 5?

function test(number) { while(number < 5) { number++; } return number; } alert(test(2)); // why does the answer return to 5? i thought while 2 < 5 then we will get 3+1 = 4 and our number will be 4.. i dont get it

16th Oct 2018, 2:04 PM
Yohanna Wilbertson
Yohanna Wilbertson - avatar
3 Answers
+ 2
4 is smaller than 5 so it will increment to 5 then the condition is false therefore returns 5
16th Oct 2018, 2:06 PM
TurtleShell
TurtleShell - avatar
+ 4
n = 2 < 5 => true => now n = n + 1 = 3 n = 3 < 5 => true => now n = n + 1 = 4 n = 4 < 5 => true => now n = n + 1 = 5 n = 5 < 5 => false And now function will return number = 5. Hope this helps ☺️☺️.
16th Oct 2018, 2:17 PM
Meet Mehta
Meet Mehta - avatar
0
all great answers thanks guys
16th Oct 2018, 3:55 PM
Yohanna Wilbertson
Yohanna Wilbertson - avatar