Pig Latin clarification

function translatePigLatin(str) {
  var pigLatin = "";
  var vowelIndex = "";
    //If word starts with vowel
    if (str[0] == "a" || str[0] == "e" || str[0] == "i" || str[0] == "o" || str[0] == "u") {
      pigLatin = str + "way";
      return pigLatin;
  else {
  for (var j=0; j<str.length; j++) {  // Locate first vowel
  if (str.charAt(j) == "a" || str.charAt(j) == "e" ||  str.charAt(j) == "i" || str.charAt(j) == "o" || str.charAt(j) == "u") {
    vowelIndex = str.indexOf(str.charAt(j));
  pigLatin = (str.substring(vowelIndex) + str.substring(0,vowelIndex) +"ay");
  return pigLatin;  


My code here works, but I don’t understand something. If I remove the return on line 9, then my code for words that start with vowels doesn’t work. My understanding was that if the first if statement was true, (meaning the word starts with a vowel) then the else part should be ignored. But, if I remove line 9, then an input such as “eight” is put through the first if statement, and then also put through the else statement giving it the incorrect translation of “eightay” Why is this?

Oops I’ve just looked at my code again and realized this is happening because of the pigLatin = (str.substring(vowelIndex) + str.substring(0,vowelIndex) +"ay"); not being inside the else function. False alarm!

1 Like