1

I'm trying to write a simple Pig Latin code. I want to check if the first letter of the input string is a vowel, if so then to run that certain code. How can I ask if y is equal to one of those values.

function pigLatin() {
    var y = prompt("Enter a word:")
    if (y.charAt(0) = a,e,i,o,u) {
        var pigLatin = y + "ay";
        document.getElementById("answer").innerHTML = "Answer is: " + pigLatin;
    } else {
        var wordLength = y.length + 1;
        var pigLatin = y.substring(1, wordLength) + y.charAt(0) + "ay";
        document.getElementById("answer").innerHTML = "Answer is: " + pigLatin;
    }
}
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
  • 2
    = assigns, == or === checks for equality (apart from the invalid syntax a,e,i,o,u) – baao Sep 12 '17 at 08:53
  • Please see [**Equality comparisons**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) – Nope Sep 12 '17 at 08:55
  • Possible duplicate of several SO posts in relation to equality of which one is https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons – Nope Sep 12 '17 at 08:56

2 Answers2

8
if (y.charAt(0) = a,e,i,o,u) {

...is not valid.

Try...

if ('aeiou'.includes(y.charAt(0))) {

Your problems are...

  • Strings must be quoted, even if they're only one character long.
  • An array must be wrapped with [ and ] (unless constructed via another means such as with the Array constructor)
  • You can't use the assignment operator (=), nor any equivalency operator (== or ===) to automatically check for the presence of an item in an array. Since you're checking against a list of single characters, you can directly use String.prototype.includes() on it.

If the user cancels the prompt(), you will get null also, which you are not handling (it will crash on the condition mentioned).

alex
  • 479,566
  • 201
  • 878
  • 984
0

First, you need the letters to be in quotes in this

if (y.charAt(0) = a,e,i,o,u)

Second, use === for equals.

Third you want it to be one of the vowels 'a', 'e', 'i', 'o', 'u'.

You could compare the indexOf the char against -1:

if (['a', 'e', 'i', 'o', 'u'].indexOf(y.charAt(0)) !== -1)
//...
doctorlove
  • 18,872
  • 2
  • 46
  • 62