-1

var b = ['a', 'e', 'i', 'o', 'u']

var inp = prompt('Enter any alphabet to check if its vowel or not').toLowerCase()

for (i = 0; i < b.length; i++) {

if(b[i]===inp){
    alert('The entered value is vowel')
    
}else{
    alert('The entered value is not vowel')
}      

}

I have tried using break after else statement but then the loop is not iterating all indexes in array. Thanks

  • You are checking if you have a match against each letter and saying yes or no. You are not seeing if it is one of the items. You need to rethink your approach. You need to only say it is not a match if does not find one in the array. You really are reinventing `.includes()` – epascarello Jul 08 '22 at 17:39

1 Answers1

0

The for loop runs once for each index of the array and so it will also execute else at least four times. A better construct would be to check whether the array holds the value using .indexOf():

var b = ['a', 'e', 'i', 'o', 'u']

var inp = prompt('Enter any alphabet to check if its vowel or not').toLowerCase()

if(b.indexOf(inp) > -1){
    alert('The entered value is vowel')
    
}else{
    alert('The entered value is not vowel')
}      

Alternatively, array.includes() could be used:

var b = ['a', 'e', 'i', 'o', 'u']

var inp = prompt('Enter any alphabet to check if its vowel or not').toLowerCase()

if(b.includes(inp)){
    alert('The entered value is vowel')
    
}else{
    alert('The entered value is not vowel')
}      

Dave Pritlove
  • 2,601
  • 3
  • 15
  • 14