Why do I pass Roman Numeral Converter, only while my variable is inside the function?

Why do I pass Roman Numeral Converter, only while my variable is inside the function?
0

#1

I passed the Roman Numeral Converter. If I place my answer variable as a global variable, my code does not work, it logs something like ‘M’ 90 times, and ‘I’ once, if i type a number such as 9001. If i place my answer variable inside of the function, it works fine. Why is this?

let decNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
let romNum = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
function convertToRoman(num) {

let answer = ''
    for (let i = 0; i < decNum.length; i++){
        while (decNum[i] <= num) {
            answer+= romNum[i];
            num-= decNum[i];
            
        }
        
      
    }
   
  return answer;
   
}

convertToRoman(4);

#2

When your code contains global variables they are changed each time the function is run. This means that after each test completes, subsequent tests 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