Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why won't this conditional display both outputs?

I’m learning about arrays and was given this assignment:

"Code an array that holds the name of your favorite bands or artists. You can name the array artists.
Using the prompt() command, ask the user to name their favorite band.

If the name of the band entered is on the array, output, “That’s one of my favorites, too.” If not, output “Sorry, not a favorite of mine.”"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can’t figure out why my code will only output one option.

Example: if I put == between choose and artists, the output is the "else" statement even if I enter a band in the array into the prompt. If it’s = it only outputs the if statement.

Here’s the code:

let artists = ["Arctic Monkeys",
                "The Black Keys",
                "Ghost",
                "Boston",
                "alt-J",
                "Fitz and the Tantrums",
                "Daft Punk",
                "Coldplay",
                "The Killers"];
let choose = prompt("What is your favorite band?");

if (choose == artists){
    alert("That's one of my favorites, too! Band Buddies!!");
} else {
    alert("Sorry, not a favorite of mine.");
}

I can’t work out what to change since it knows the two options in the conditionals, just something seems to be off with the booleans or something.

Thanks in advance for your help!

>Solution :

Prompt returns a string, but you are comparing it to an array.

There are many solutions to this, a simple solution is to use array.includes(string).

Includes will search the array for the string that you pass to it.

let artists = ["Arctic Monkeys", "The Black Keys", "Ghost", "Boston", "alt-J", "Fitz and the Tantrums", "Daft Punk", "Coldplay", "The Killers"];
let choose = prompt("What is your favorite band?");

if (artists.includes(choose)) {
  document.getElementById("output").innerHTML = "That's one of my favorites, too! Band Buddies!!";
} else {
  document.getElementById("output").innerHTML = "Sorry, not a favorite of mine.";
}
<div id="output"> </div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading