JavaScript Algorithms and Data Structures Projects - Roman Numeral Converter

Tell us what’s happening:
Describe your issue in detail here.
Hello, I have this lazy code. I just wrote one while loop and could then just copy it and change it’s values.

It’s working though. It returns the correct things, but it says that the correct string isn’t being returned.
Your code so far

let roman = [];



function convertToRoman(num) {
  while (num >= 1000) {
    num -= 1000;
    roman.push("M")
    console.log(roman);
  }
  while (num >= 900) {
    num -= 900;
    roman.push("CM")
    console.log(roman);
  }
  
  while (num >= 500) {
    num -= 500;
    roman.push("D")
    console.log(roman);
  }
  while (num >= 400) {
    num -= 400;
    roman.push("CD")
    console.log(roman);
  }
  while (num >= 100) {
    num -= 100;
    roman.push("C")
    console.log(roman);
  }
  while (num >= 90) {
    num -= 90;
    roman.push("XC")
    console.log(roman);
  }
  while (num >= 50) {
    num -= 50;
    roman.push("L")
    console.log(roman);
  }
  while (num >= 40) {
    num -= 40;
    roman.push("XL")
    console.log(roman);
  }
while (num >= 10) {
    num -= 10;
    roman.push("X")
    console.log(roman);
  }
  while (num >= 9) {
    num -= 9;
    roman.push("IX")
    console.log(roman);
  }
while (num >= 5) {
    num -= 5;
    roman.push("V")
    console.log(roman);
  }
  while (num >= 4) {
    num -= 4;
    roman.push("IV")
    console.log(roman);
  }

while (num >= 1) {
    num -= 1;
    roman.push("I")
    console.log(roman);
  }
  
  let allt;
 for (let a = 0; a < roman.length; a++) {
   if (allt == undefined) {
    allt = roman[a];
  }
  else {
  allt += roman[a];
  }
 }
return allt;
}

console.log(convertToRoman(44));

Your browser information:

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

Challenge: JavaScript Algorithms and Data Structures Projects - Roman Numeral Converter

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each function call completes, subsequent function calls start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

Oh I totally missed that since it all resets as soon as I change the code either way on this website! Thank you very much.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.