Tom
Tom

Reputation: 25

Else statement not working

I am trying to return the longest even word in the array using a forEach loop and return "00" when there is no even word. I am able to get the part of returning the longest even word to work correctly, but when I introduce the else statement it doesn't work anymore:

function FindlongestWord(input) {
  var arrWords = input.split(' ');
  var wordlength = 0;
  var word = '';
  arrWords.forEach(function(wrd) {
    if (wordlength < wrd.length && wrd.length % 2 == 0) {
      wordlength = wrd.length;
      word = wrd;
    } else  {
      return "00";
    }
  });
  return word;
}

Upvotes: 2

Views: 2170

Answers (2)

isnot2bad
isnot2bad

Reputation: 24454

As others already explained: The forEach function ignores the return value of the callback function, so it is useless to return '00' there.

Here is another solution that uses filter and reduce instead of forEach. It does not need to hold and update variables outside of the callbacks:

function FindLongestEvenWord(input) {
    var arrWords = input.split(' ');
    var r = arrWords.filter(function(w) {
            return w.length % 2 == 0;
        }).reduce(function(res, w) {
            return (w.length > res.length) ? w : res;
        }, "");
    return r == "" ? "00" : r;
}

Upvotes: 0

Dij
Dij

Reputation: 9808

your return "00" statement only returns from the inner function and not from FindlongestWord(input) function.

you can initialize your word with "00". then it will return "00" if it is not set inside forEach.

function FindlongestWord(input) {
var arrWords = input.split(' ');
var wordlength = 0;
var word = '00';
arrWords.forEach(function(wrd) {
   if (wordlength < wrd.length && wrd.length % 2 == 0) {
      wordlength = wrd.length;
      word = wrd;
   }
});
return word;
}

Upvotes: 3

Related Questions