Pig Latin - Don't know what's the problem with my code

Tell us what’s happening:
I have written this code below for this particular challenge but I don’t know where it went wrong?
What do I need to change in my code?

Your code so far


function translatePigLatin(str) {
  var newString = str.split("");
  var newArr = [];
  if(newString[0] === 'a' || 'e' || 'i' || 'o' || 'u') {
    return newString.join("") + "way";
  }
  else {
    for (var i = 0; i < newString.length(); i++) {
      if(newString[i] !== 'a' || 'e' || 'i' || 'o' || 'u') {
        newArr.push(newString[i]);
        newString.shift();
      }
      var joint = newArr.join("");
      return newString.join("") + joint + "ay";
      break;
    }
    
  }
}

translatePigLatin("consonant");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36.

Link to the challenge:

It’s due to two issues. Issue number one, and probably the most glaring issue, is your use of || operator. The way you’re using it is checking each expression before the next ||, and if it is truthy, using that expression. In plain English:

  • Does newString[0] equal 'a' || Does 'e' equal true || Does 'i' equal true || etc.

Because you’re checking for 'constant', the if statement is asking first, does 'c' equal 'a', but then it disregards 'c' altogether. If you console this out, you’ll get the following:

console.log('c' === 'a' || 'e' || 'i' || 'o' || 'u')
// logs 'e' because 'e' by itself is considered truthy

This is a common mistake that I did a lot when I first learned this trick, too :sweat_smile: If you want to keep this logic, you’ll have to set a statement for each case, similar to how you’ve written newString[0] === 'a'. However, I recommend using .match() with regular expressions.

Another way you could hack it to a single line is by using .includes().

The other error you have in your code will trigger once you’ve fixed the first error. Your for loop is using the length property on the newString value as a function, but length is not a function.

If you fix those two errors, it will work as expected.

1 Like

Thanks a lot for this detailed reply. I’ll change my code as per your directions.
Thanks again! :slight_smile:

1 Like

I changed my code as follows:

function translatePigLatin(str) {
  var newString = str.split("");
  var regex = /[aeiou]/gi;
  if(newString[0].match(regex)) {
    return newString.join("") + "way";
  }
  else if (!str.match(regex)) {
    return str + "ay";
  }
  else {
      while (!newString[0].match(regex)) {
        var Char = newString.shift();
        newString.push(Char);
        
      }

      return newString.join("") + "ay";
  }
  
}

And it is passing all test cases! Yay :grinning:

1 Like