0

I'm a newbie on Javascript and I'm trying to do some exercises. I have found other ways on here that are more efficient at solving this, but anyway, here's how I tried doing it:

var char = prompt("Give me a letter");
char = char.toLowerCase();

function isVowel(char){
  var vowels = new Array('a','e','i','o','u');

  for(i = 0; i < vowels.length; i++){
    if(vowels[i] == char){
      return "This letter is a vowel.";
    }else{
      return "This letter is not a vowel.";
    }
  }
}
alert(isVowel(char));

Now, I understand this isn't the best way to do this, but I'd like to understand what's wrong with my for loop, since "a" is the only letter it recognizes as being a vowel. Can someone point me out the reason why it isn't running trough the whole array?

Thanks in advance

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Spner
  • 15
  • 1
  • 4
    The reason it isn't running through the whole array is because you `return` a value. That stops the function after the first iteration. – showdev Nov 15 '13 at 22:49
  • it should be: for (var i = 0; i < vowels.length; i++) – milestyle Nov 15 '13 at 22:50
  • 2
    Ya remove the else condition from the loop and place the return at the end of is vowel (after you have checked each character in `vowels`) – megawac Nov 15 '13 at 22:50

3 Answers3

3

You should not return until you have a definite "yes" or "no" answer.

Try something like this instead:

var char = prompt("Give me a letter");
char = char.toLowerCase();

function isVowel(char){
  var vowels = new Array('a','e','i','o','u');

  for(i = 0; i < vowels.length; i++){
    if(vowels[i] == char){
      return "This letter is a vowel.";
    }
  }
  return "This letter is not a vowel.";
}
alert(isVowel(char));
paulsm4
  • 114,292
  • 17
  • 138
  • 190
2
var char = prompt("Give me a letter");
char = char.toLowerCase();

function isVowel(char){
  var vowels = new Array('a','e','i','o','u');
  var isv = false;

  for(i = 0; i < vowels.length; i++){
    if(vowels[i] == char){
      isv = true;
      }
    }
  if( isv == true)
     return "This letter is a vowel.";
  else
     return "This letter is not a vowel.";
  }
}
alert(isVowel(char));
T-D
  • 1,306
  • 1
  • 16
  • 23
1

The reason it isn't running through the whole array is because you return a value. That stops the function after the first iteration.

Here's a simpler solution to identify vowels without having to loop through an array:

function isVowel(char) {

    if (vowels.indexOf(char) >= 0) {
        return "The character \""+char+"\" is a vowel.";
    } else {
        return "The character \""+char+"\" is NOT a vowel.";
    }

}

var vowels = new Array('a','A','e','E','i','I','o','O','u','U');

alert(isVowel('e'));
alert(isVowel('f'));

The indexOf functionality is based on the answer here.

Here's a working example (jsFiddle).

Community
  • 1
  • 1
showdev
  • 28,454
  • 37
  • 55
  • 73