I just wondered why is my code giving me an infinite loop and will it actually work

Tell us what’s happening:
The outer while loop is giving me an infinite loop. In addition, I wonder if the code is actually correct and will it pass the challenge.

  **Your code so far**

function convertToRoman(num) {
let myArr = []
while (num>0){
  while (num%100===0)
  {if(num%1000 === 0){
    myArr.shift("M")
    num -= 1000
  }else if(num===900){
    myArr.shift("CM")
    num -= 900
  }else if(num===500){
    myArr.shift("D")
    num -= 500
  }else if (num===400){
    myArr.shift("CD")
    num -= 400
  }else if(num<900&&num!=500&&num!=400){
    myArr.shift("C")
    num -= 100
  }}

  while (num%10===0){
  if(num===90){
    myArr.shift("XC")
    num -= 90
  }else if (num === 50){
    myArr.shift("L")
    num -= 50
  }else if (num === 40){
    myArr.shift("XL")
    num -= 40
  }else if(num<90&&num!=50&&num!=40){
    myArr.shift("X")
    num -= 10
  }}
  
  if(num%5===0){
    myArr.shift("V")
    num -= 5
  }else if(num===9){
    myArr.shift("IX")
    num -= 9
  }else if (num===4){
    myArr.shift("IV")
    num-=4
  }else if(num<9&&num!=5&&num!=4){
    myArr.shift("I")
    num-=1
  }
}
}

convertToRoman(36);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36

Challenge: Roman Numeral Converter

Link to the challenge:

Little testing around makes it quite clear: You only check if num is bigger than 0 at the very start - if any loop in the middle makes num < 0, you don’t catch that.
So if num is 10 → it will constantly reduce it by 10 and add an “X” infinitly… well it “would” if you actually used the correct method. You use .shift() which removes elements from an array.

There might be more issues, I only tested it a little and got that out. You might want to overthink this method.

2 Likes

oh thanks a lot for your insights I will rework work it and hope for the best.