Cookie Cookie - 1 year ago 103
Javascript Question

while loop javascript logic

Can anybody explain this while loop for me? It part of the roman numeral challenge on free code camp - it's not mine, I did my own but it was much more code. I'm trying understand this one to improve my own. Anyway, the while loop is totally throwing me. Any help would be awesome.

function romans(num){
var roman = "";
var romanNumerals = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
var numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1];

for (var i=0; i<numbers.length; i++) {
//If the num was 5 then then it would read 5 greater than 1000?
while (num >= numbers[i]) {
roman = roman + romanNumerals[i]
//5 minus 1000?
num = num - numbers[i]

return roman;


Answer Source

num starts as the desired input, then you find the numbers that add up to num, starting at the biggest roman numeral (numbers[0]).

You repeat with the while loop because you might need multiple copies of the letter (i.e. "III" == 3)

romans(5) will not trigger the while loop until numbers[10] (because as you say 5 >= 1000 == false,) at this point you append the character V to roman, and subtract 5 from num. The while loop will never again trigger since num is now 0.

Try thinking through it with romans(3001) and you will see the while loop trigger 3 times for M/1000, then get skipped 10 times, then trigger once for I/1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download