Roman Numeral Converter undefined error

Roman Numeral Converter undefined error
0

#1

I do not have correct logic yet, but while I am working on to get my logic right, I need help for 'undefined…" error at return statement.

code start below…

function convertToRoman(num) {
  
 var numRomObj = { 1:"I", 2:"II",3:"III", 4:"IV", 5:"V",6:"VI", 7:"VII", 8:"VIII",9:"IX", 10:"X", 40:"XL", 50:"L", 90:"XC",100:"C",400:"CD", 500:"D", 900:"CM", 1000:"M", 2000:"MM", 3000:"MMM" };
  
 var romanNum; 
 var numArray = num.toString().split("");// for num = 36 answer is ["3',"6"]
  var l = numArray.length;
  for (var i = 0; i <= l; i++){
    
    var j = numArray[i];
    romanNum += numRomObj[j];
    
  }
  
  return romanNum;//undefinedIIIVIundefined
 
}

convertToRoman(36);

#2

The first undefined is because romanNum starts out as undefined. Declare it as a blank string, var romanNum ='';

The second one is because you index through the array too far. It wouldn’t be <= but just <, which is fairly common with indexing. You’ve indexed too far and there is no property there in the object.

A note: Watch your variable naming.

For example, I wouldn’t have a variable l (the letter) because it is too easily confused with 1 the number. In some fonts they are the same symbol. Why not give it it a meaningful name like len or not use a variable at all and just put numArray.length in there.

Also, j is very commonly used for iteration variables, often i, then j, then k. It was a comprehension speed bump for me as I assumed it was part of a loop I wasn’t seeing. I would either name it something meaningful, or (again) just skip it all together and just use that as your array index, romanNum += numRomObj[numArray[i]]; You can build an argument that it’s clearer if you set it to a variable first, but make the name meaningful.

Neither of these is wrong per se, just things that might confuse other people reading your code. And might confuse you if you come back to it after a year. There are certain conventions - it’s good to know them.


#3

Thank you very much for troubleshooting my issue. I also appreciate your suggestions about naming conventions which does make sense. I did solve the challange with your help. Thanks.


#4

There is one problem in your code for why you see the undefined at the beginning and and a different problem for why undefined is on the end.

For the one on the beginning, inside your for loop, you have:

  romanNum += numRomObj[j];

The first time the for loop is entered, romanNum (even though declared), has not been initialized to a particular value, so JavaScript assigns it the value undefined. So in the first iteration you are basically doing:

  romanNum = undefined + 'III'

For the one at the end, in your for loop condition, you have:

  i <= l;

so since array are zero indexed, during the last iteration of the for loop, i = 2 and since there is no numArray[2], JavaScript assigns it the value undefined.