JS Troubleshooting #1/Part 2: Swapping for loops out with array methods

In my last blog post about my Horoscope project, I added the functionality of letting a button click initialize the app program and further enabling a simple retrieval of a daily horoscope based on the the User’s sign. In this post I will explain how the input of the user is collected and how we can determine if the input of the user is within the list of zodiac signs the code has data and content for.

Using the code segment above, I have implemented a code that starts after the user clicks the button and a dialog box requesting information appears on the browser window.

First, I set a variable for the user input of the alert box with the following code

let userPrompt=prompt("What is your zodiac sign?");

Then, I create an array that will contain all the zodiac signs a user may input, including both capitalizations to accommodate for variation in the user input.

let zodiac=["Capricorn","capricorn","Aries","aries","Taurus","taurus","Virgo","virgo","Sagittarius","sagittarius","Aquarius","aquarius","Pisces","pisces","Leo","leo","scorpio","Scorpio","Libra","libra","Cancer","cancer","Gemini","gemini"];

It’s possible that there is a shorter method to account for both variations of spelling in a shorter manner, though I’m not sure yet what it could be. For now, I am using this object.

Initially, I wanted to show an alert to let the user know the app did not have the information for their sign and to try again if the user entered in the wrong information or misspelled. Before I decided to figure out how to add this functionality, I did not have any for loops or array methods on my code as I do now. I could have left the code without, but the app would not respond or do anything if the user input did not match any of the signs I had designated in the zodiac object.

I decided to type in a query, probably something along the lines of “loop through array to determine incorrect user input” through google in regards to wanting to find a best method for implement user input validity and found some information on this stack overflow thread . When I initially saw this post, I took the for loop that was mentioned at the top and implemented it into my code, as such:

// let userPrompt=prompt("What is your zodiac sign?");
// let zodiac=["Capricorn","capricorn","Aries","aries","Taurus","taurus","Virgo","virgo","Sagittarius","sagittarius","Aquarius","aquarius","Pisces","pisces","Leo","leo","scorpio","Scorpio","Libra","libra","Cancer","cancer","Gemini","gemini"];
// let isMatchFound = false;

// for(var x=0; x<zodiac.length; x++) {
//   console.log(zodiac[x]);
//   if(zodiac[x]===userPrompt){
//     isMatchFound = true;
//     break;
//   }
// }
// if(!isMatchFound){
//   console.log("Match not found!");
//   alert("Uh oh! I don't have a horoscope for that sign. Please try again.");

It worked, and gave an alert to the user if their input didn’t not match the object as well as let the rest of the code run. The conditional statements following the for loop would be executed if the user input matched anything in the zodiac array, and each conditional statement furthermore enabled the appearance of each information box that would appear correspondent to each Zodiac sign.

Upon looking at the stack overflow thread once again, I had noticed someone suggest that a for loop was not needed for this functionality, and that one could use this code instead:

if(cars.indexOf(userPrompt) !== -1){    
    // your code
} else {

Since I had not seen this suggestion before, I decided to further google what that function did. It turns out that this specific type of boolean expression is part of a native implementation of built-in Javascript functions used specifically with arrays called Array Methods. So how would this replace my ‘for loop’ that was running through my array to determine if my user input matched? I could use indexOf(), which will ‘search the array for an element and returns its position’. I went ahead and implemented the indexOf() example into my code and ended up with this result:

let userPrompt=prompt("What is your zodiac sign?");
let zodiac=["Capricorn","capricorn","Aries","aries","Taurus","taurus","Virgo","virgo","Sagittarius","sagittarius","Aquarius","aquarius","Pisces","pisces","Leo","leo","scorpio","Scorpio","Libra","libra","Cancer","cancer","Gemini","gemini"];

 if(zodiac.indexOf(userPrompt) >=0){
if  (userPrompt == "Gemini" || userPrompt == "gemini") {
    document.querySelector('#Gemini').style.visibility = 'visible';
    document.querySelector('#Gemini').style.display = 'block';

I liked this implementation because it not only shortened and cleaned up my code, I did some additional research on its performance in terms of load time and it turns out that this array method actually returns the value faster than one would using a for loop. It may not make a difference on such a small scale, but in more complex and large application builds, the small differences in time can start to add up and result in lagging browser display and performance load time so I think it is important to think about. I understand this function is working the way I want it to, but it is a bit more opaque compared to the clarity of the for loop.

I’ve happily stumbled into the more complex world of native implementation and built-in functions which may be a bit ahead of my current knowledge of JS, but in learning how to search for what I needed and experimenting with working the new code into my existing one, I have been able to see the potentials that may come by using modular elements without having to fully hardcode each individual step like one would with for and while loops. That potential is super exciting in terms of learning web development. In terms of the way I have the indexof() function implemented in my code, I plan to learn exactly how it functions down to each bit soon and am looking forward to reaching out to others who may know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s