+ 2

Guys please help me explain the output of these while loop code.

function brown (num) { var red = " "; while (num > 0){ red = num % 2 + red; num = Math.floor(num/2); } return red; } document.write(brown(4));

16th Oct 2017, 10:30 PM
Novich
Novich - avatar
4 Answers
+ 9
The function "brown(4)" is called inside the document.write so that makes num equivalent to 4, the variable red is declared as an empty string and then since 4 is more than 0 the while loop is entered. "red = num % 2 + red" means red = 4 % 2 + " ", 4 % 2 is 0 and 0 + " " is "0" (as a string since red was declared as a string), num is halved so is now 2 and since 2 is more than 0 the loop continues... "red = num % 2 + red" is now red = 2 % 2 + '0', 2 % 2 is 0 and 0 + '0' is "00", num is again halved so is now 1 and 1 is more than 0 so the loop still continues... "red = num % 2 + red" is now red = 1 % 2 + '00', 1 % 2 is 1 and 1 + '00' is "100", num is once again halved to 0.5 and this time Math.floor takes effect since that is a decimal and makes num 0, 0 is not more than 0 so the loop is exited and the value of red is return in place of the "brown(4)" and the value of red ("100") is written to the screen. Edit: No Problem :)
17th Oct 2017, 12:26 AM
LynTon
LynTon - avatar
+ 1
Thanks a lot, you made it so clear to my understanding.
17th Oct 2017, 5:27 AM
Novich
Novich - avatar