0
monthDateMapper(month) {
  const months = {'Jan': '01', 'Feb': '02', 'Mar': '03'
                ,'Apr': '04', 'May': '05', 'Jun': '06'
                ,'July': '07', 'Aug': '08', 'Sep': '09'
                , 'Oct': '10', 'Nov': '11', 'Dec':'12'}
  let monthDate;
  for(var monthAbrev in months) {
    month === monthAbrev ? monthDate = months[monthAbrev] : monthDate = 'Invalid Value'
  }
  return monthDate
}

Presuming I hit my function with monthDateMapper('Apr'), why does my conditional never assign monthDate to be 04.

I've read a few articles on the subject of matching strings in Javascript; most of them say that this kind of type checking is never going to be true, even if both types are strings and the same value:

One of the answers suggested to use lodash _.isEqual(), this did not work. Also I tried converting lower-case on both sides, also trying to convert them both further to 2 strings. I confirmed they were both two strings through typeOf.

Is there a way around it?

3 Answers3

2

Because you loop 12 times. One of those times, monthDate is assigned the value 04, but the other 11 times it is assigned the value Invalid Value. Unless the correct value is assigned on the last iteration of the loop, it is simply overwritten with Invalid Value.

As Andy noted, your code can be reduced to:

monthDateMapper(month) {
  const months = {'Jan': '01', 'Feb': '02', 'Mar': '03'
                ,'Apr': '04', 'May': '05', 'Jun': '06'
                ,'July': '07', 'Aug': '08', 'Sep': '09'
                , 'Oct': '10', 'Nov': '11', 'Dec':'12'}
  return months[month] ? months[month] : 'Invalid Value';
}
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
2

You are iterating over all the keys and you are not stopping the iteration when your condition is true. BTW you do not need to iterate over the months :)

function monthDateMapper(month) {
   const months = {'Jan': '01', 'Feb': '02', 'Mar': '03'
            ,'Apr': '04', 'May': '05', 'Jun': '06'
            ,'July': '07', 'Aug': '08', 'Sep': '09'
            , 'Oct': '10', 'Nov': '11', 'Dec':'12'}

  return months[month] || 'Invalid Value'
};
1

You compare 12 times and you assign 12 times, so the last compare is for Dec which assigns 'Invalid value'. This is caused by flawed logic on multiple levels.

I think you'd better use an array of month names and indexOf():

function monthDateMapper(month) {
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  var index = months.indexOf(month);
  return index == -1 ? 'Invalid Value' : index + 1; // or (index+1).toString() if needed
};

console.log(monthDateMapper('Jan'));
console.log(monthDateMapper('Apr'));
console.log(monthDateMapper('Dec'));
console.log(monthDateMapper('ZZZ'));

PS Note that I also changed 'July' to 'Jul' for consistency.

Peter B
  • 22,460
  • 5
  • 32
  • 69