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.”"
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!
3
Answers
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.
this happens because you’re not accesing to the values of the array.
With your comparison "if(choose == artists)", you’re comparing a string (choose variable) and an array (artists).
To check if the array has the value written by the user you can use:
Try it!
This solution also uses
.includes()
to compare strings, but with the added advice that you should handle user input differently..includes()
is case-sensitive so should the user input "the killers", your result would befalse
. In the example below,.toLowerCase()
is used on the "artists" array as well as the user input "choose".