JS exercise 2, Roman numbers

I want to know why my code doesn’t function as an answer.
Code:

const array=[ ];
function convertToRoman(num){
 const romanNumbers=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
 const romanDigits=[1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
for(let i=0;i<romanDigits.length;i++){
    while(num>=romanDigits[i]){num-=romanDigits[i];
    array.push(romanNumbers[i]);
    };
}
console.log(array);
return array;}

I finally solved it!

Summary
var array = [];
const romanNumbers=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
 const romanDigits=[1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];

function convertToRoman(num){
for(let i=0;i<romanDigits.length;i++){
    while(num>=romanDigits[i]){
    num-=romanDigits[i];
    array.push(romanNumbers[i]);};
}
array=array.join("");
return array;}

Let me format this for human readability.

const array = [];
function convertToRoman(num) {
  const romanNumbers = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
  const romanDigits = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  for (let i=0;i<romanDigits.length;i++) {
    while (num>=romanDigits[i]) {
      num -= romanDigits[i];
      array.push(romanNumbers[i]);
    };
  }
  console.log(array);
  return array;
}

That global variable holding the array is a problem. You shouldn’t change a global variable while your function executes. Your function will only run once.

Also, you need to return a string, not an array.

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