What is the reason behind this code's ability to detect vowels as well as other

I'm currently working on debugging a specific portion of code for my class. I'm having trouble understanding why this JavaScript code is counting all letters instead of just vowels.

var text, i, sLength, myChar;
var count;
var text = prompt("Please type a phrase"); //changed to "phrase" and fixed ' to "
count = 0;
for (i = 1; i <= text.length; i+= 1){
    myChar = text[i];
    if (myChar == 'a' || myChar == 'o' || myChar == 'e' || myChar == 'u'){ //modified the conditionals for checking vowels
        count += 1;
        console.log('Vowel:', myChar);   
    }
    console.log(myChar, count);
}
alert(count); //moved count into ()

Answer №1

The comparison line is not executing the check correctly. It should read as follows:

if (myChar == 'a' || myChar == 'o' || myChar == 'e' || myChar == 'u')

Answer №2

Here is the corrected JavaScript code:

var text, i, sLength, myChar;
var count;
var text = prompt("Type a phrase please");
count = 0;
for (i = 1; i <= text.length; i+= 1){
    myChar = text[i];
    if (myChar == 'a' || myChar == 'o' || myChar =='e' || myChar == 'u'){ 
        count += 1;
        console.log('Vowel:', myChar);   
    }
    console.log(myChar, count);
}
alert(count)

The issue with your original code is that it incorrectly evaluates whether 'o' is true in the expression || 'o'. Since a string literal like 'o' is not a falsy value, the condition stays true for every iteration of the loop.

Answer №3

Quick and Easy Vowel Count

function countVowels (string) {
    return string.match(/a|e|i|o|u/g).length;
}

Try it out like this:

alert(countVowels(prompt("Enter a phrase")));


Your if statement is not valid. For a simple check on multiple options, consider using the following method:

if (['a', 'e', 'i', 'o', 'u'].indexOf(myChar) > -1) {
}


Another Handy Function!

function hasOptions (c) {
    return arguments.splice(1).indexOf(c);
}

Then

if (hasOptions(myChar, 'a', 'e', 'i', 'o', 'u'))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an XML response to generate an HTML dropdown menu in PHP

My onChange function in javascript calls a PHP file to fetch UPS rates and update an HTML dropdown list. Everything was working fine until I needed to add an item to the options list based on a comparison. Javascript: function fetch_UPS(el){ var zip = ...

"How can I make a dropdown open and close when a button is clicked, but also close when clicking outside of it at the same

One button click opens a dropdown, and it also closes when clicked outside. toggleAllCategories() { this.setState({ isOpenAllCategories: !this.state.isOpenAllCategories }); } The issue arises when attempting to open and close the dropdown by clic ...

Using pdfkit to create a PDF and then returning it as a base64 string from a function

I am attempting to utilize PDFKit to produce a PDF file and then retrieve it as a base64 string. Here is the code snippet I am using: function generatePDFDocument(data){ let doc = new PDFDocument(); var bufferChunks = []; doc.on('readabl ...

optimal application of css with jquery

I have a question about using jQuery to set the padding of a class or id. I am able to successfully change the height of an element with this code: $('.menu').css({ height: '90px' }); But now, I need to apply a specific CSS rule in jQ ...

The SCONS PDB seems to be struggling to locate my file, even though I have specifically added it to the system path

Attempting to troubleshoot a scons file with the command: scons --debug=pdb. When setting a breakpoint in SConstruct using b SConstruct:24, an error is encountered: *** 'SConstruct' not found from sys.path The SConstruct file resides in the cu ...

Uploading Files with PhoneGap using Ajax

I have been attempting to execute this PhoneGap example for uploading images from a device to a server. // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // functi ...

Transferring variables from the $(document).ready(function(){}) to the $(window).load(function(){} allows for seamless and

Just think about if I successfully create percent_pass at the time of document.ready, how can I transfer that variable to window.load? $(document).ready(function() { jQuery(function() { var ques_count = $('.question-body').length; va ...

Adding optional properties to TypeScript interfaces

As discussed in this post, the optional ? operator is commonly used to indicate that a function parameter can be omitted. But what is the significance of the ? operator when it appears on interface parameters? For instance, consider the following TypeScrip ...

Is there a way to adjust user privileges within a MenuItem?

One of my tasks is to set a default value based on the previous selection in the Userlevel dropdown. The value will be determined by the Username selected, and I need to dynamically update the default value label accordingly. For example, if "dev_sams" is ...

What is the best method for dynamically increasing the data in a shopping cart?

My goal is to stack cart items dynamically every time the addProduct() function is called. I've successfully captured the data, but I'm facing an issue where the quantity always remains at 1 on each function call. Here's the logic I've ...

Error: Unable to authenticate due to timeout on outgoing request to Azure AD after 3500ms

Identifying the Problem I have implemented SSO Azure AD authentication in my application. It functions correctly when running locally at localhost:3000. However, upon deployment to a K8s cluster within the internal network of a private company, I encounte ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...

Tips for personalizing react-show-more text length with Material-UI Icons

In my SharePoint Framework webpart using React, I am currently utilizing the show more text controller. However, I am interested in replacing the "Show More" and "Show Less" string links with the ExpandMore and ExpandLess Material UI icons. Is there a way ...

tips for sending the database value to the next page with ajax

Struggling to send the database value retrieved through ajax to the next page. Tried several methods but none seem to work. Could anyone provide guidance on how to achieve this? php Successfully connected to the database $sql = "SELECT * FROM `billin ...

Modifying URLs with backbone.js

When it comes to my Backbone module, I typically access it via the URL: http://localhost/src/index.html#test_module However, there is another module that I need to view which can be accessed using the URL: http://localhost/src/index.html#test_module ...

Implement a procedure for printing a page once the columnize operation has been completed

Hello, I have run into a problem that I need help with. Currently, I am trying to print a page after the function "columnize" has finished its task. However, the print function is executing before the columnize function completes. How can I ensure that t ...

Adjust speed on various HTML5 video players

I'm looking to slow down all the HTML5 video players on my page to 0.5x speed. Currently, I have a JavaScript snippet that only affects one video player at a time. <script type="text/javascript"> /* play video twice as fast */ document.quer ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

Benefits of utilizing minified AngularJS versions (Exploring the advantages of angular.min.js over angular.js, along with the inclusion of angular.min.js.map)

After introducing angular.min.js into my project, I encountered a problem. http://localhost:8000/AngularProject/angular.min.js.map 404 (Not Found) angular.min.js.map:1 Upon further investigation, I discovered that including angular.min.js.map resolve ...

What are the best practices for utilizing ESM only npm packages alongside traditional npm packages within a single JavaScript file?

Hey there, I'm fairly new to web development and I encountered a problem when trying to require two packages, franc and langs, in my index.js file. It turns out that franc is now an ESM only package, requiring me to import it and mention type:module i ...