lkhaoua
lkhaoua

Reputation: 13

if statment always executing

I am trying to solve this simple algorithm that change a string depending on the first character, it always run on (If) even if it doesn't meet it requirement; i can just check the "freecodecamp" for answer but i want some one to explain to me why it never get to the else statement thanks

let translatePigLatin = str => {


let myArr = str.split("")
  let arr = [...myArr]
  if(arr[0] === "a" || "e" || "u" || "i" || "o"){
    return [...arr,"w","a","y"].join("")
  }else{
    let firstChar = arr.shift()
    arr.push(firstChar)
     console.log(arr)
    return [...arr,"a","y"].join("")
  }
 
}
console.log(translatePigLatin("algorithm"));

Upvotes: 0

Views: 22

Answers (2)

You just need rewrite your condition to the next:

if(arr[0] === "a" || arr[0] === "e" || arr[0] === "u" || arr[0] === "i" || arr[0] === "o")

you can extract condition to the method, it will be more readable

Upvotes: 0

mlibby
mlibby

Reputation: 6724

if(arr[0] === "a" || "e" || "u" || "i" || "o")

This is always true because it is comparing arr[0] to "a", then checking the truth value of string "e" etc. Those following values are always true. You need something like:

if(arr[0] === "a" || arr[0] === "e" || arr[0] === "u" || arr[0] === "i" || arr[0] === "o")

or

if("aeiou".includes(arr[0]))

Upvotes: 1

Related Questions