Mike Wazowksi
Mike Wazowksi

Reputation: 43

Javascript if statement or operator not working

"use strict";

function vovelsAndConstants(s) {

  let vowels = new Array();
  let constants = new Array();

  for (let a = 0; a < s.length; a++) {
    //console.log(s[a]);
    if (s[a] === "a" || "e" || "i" || "o" || "u") {
      console.log(s[a]);
    }
  }
 
}

vovelsAndConstants("sosisvesalam");

I can't understand why or operator here doesn't work It all makes sense to me. It outputs all chars instead of vowels

Upvotes: 2

Views: 228

Answers (4)

Marios
Marios

Reputation: 27348

IMO the easiest way is to use includes, otherwise you will have to list all the different comparisons separately.

Replace:

s[a] === "a" || "e" || "i" || "o" || "u"

with:

["a","e","i","o","u"].includes(s[a])

or as Thomas suggested in his comment:

"aeiou".includes(s[a])

These will do a string comparison and not a type comparison as === would do but it could still work for you.

Upvotes: 4

Majed Badawi
Majed Badawi

Reputation: 28414

You need to check for equality for each case:

function vovelsAndConstants(s) {
  const vowels = new Array();
  const constants = new Array();
  for (let a = 0; a < s.length; a++) {
    if (s[a] === "a" || s[a] === "e" || s[a] === "i" || s[a] === "o" || s[a] === "u") {
      console.log(s[a]);
    }
  }
}

vovelsAndConstants("sosisvesalam");

Another way using .indexOf:

const VOWEL_LETTERS = ["a","e","i","o","u"];

function vovelsAndConstants(s) {
  const vowels = new Array();
  const constants = new Array();
  for (let a = 0; a < s.length; a++) {
    if (VOWEL_LETTERS.indexOf(s[a]) !== -1) {
      console.log(s[a]);
    }
  }
}

vovelsAndConstants("sosisvesalam");

Upvotes: 1

Mamun
Mamun

Reputation: 68933

Your current condition only compare the a character successfully. From the second check all comparison segment is true, hence outputs all the characters.

You have to compare the currently iterated character with all possible vowels in the condition:

"use strict";

function vovelsAndConstants(s) {

  let vowels = new Array();
  let constants = new Array();

  for (let a = 0; a < s.length; a++) {
    if (s[a] === "a" || s[a] ==="e" || s[a] ==="i" || s[a] ==="o" || s[a] ==="u") {
      console.log(s[a]);
    }
  }
 
}

vovelsAndConstants("sosisvesalam");

Upvotes: 1

Dark Hippo
Dark Hippo

Reputation: 1265

It makes sense to you based on the language we speak, whereas with programming you have to be explicit.

if (s[a] === "a" || s[a] === "e" || s[a] === "i" || s[a] === "o" || s[a] === "u") {
   console.log(s[a]);
}

JavaScript doesn't know what you are comparing "e" or "i" or "o" to, you need to tell it every time.

Upvotes: 1

Related Questions