Search code examples
javascriptstringloopsreturnslice

JavaScript: Loop through string and return string + 'ay' if string contains vowel in first letter


I am trying to run a function that does pig latin. I'm stuck on one of the first steps.

When I set the input argument equal to 'eat' => I want my code to return the string plus 'ay'. Please see code below for if statement as well.

Instead, when I run my code it returns undefined. I want it to return 'eatay'. Why?

// Pig Latin

const pigify = (str) => {

  let sentSplit = str.split(' ')
  //console.log(sentSplit)

  for (let i=0; i<sentSplit.length; i++){
    //console.log(sentSplit[i])
    let element = sentSplit[i]

    console.log(element[0])

    if (element[0].includes('a', 'e', 'i', 'o', 'u')){
      return `${element}ay`
    }

    // else if (!str[0].includes('a', 'e', 'i', 'o', 'u') && !str[1].includes('a', 'e', 'i', 'o', 'u')){
    //   return `${str.slice(2)}${str.slice(0,2)}ay`
    // }

    // else if(!str[0].includes('a', 'e', 'i', 'o', 'u')){
    //   return `${str.slice(1)}${str[0]}ay`
    // }
  }
}

pigify('eat')

Solution

  • You have the arguments to includes() wrong. The syntax is container.includes(element), so it should be:

    if (['a', 'e', 'i', 'o', 'u'].includes(element[0])) {