i’m in a very beginner javascript course and we were tasked with making a simple loop "program". I settled on asking users for names of colors and based on how many answers they come up with, it would display some kind of result message.
I got the initial question prompt to work asking for color names but no matter what i do or where I try to put my alert code, it doesn’t seem to work, any guidance on where to go from here? tried changing i in the alert pop up statements to colorNames and cName but still nothing
// variable for while loop
var colorNames = [];
var keepRunning = true;
// keep naming colors until done
while (keepRunning) {
var newColor = prompt('Name as many colors as you can!' + "n" + 'If you can't think of any more, leave empty and hit OK.');
//test if prompt box has something in it or not
if (newColor.length > 0) {
colorNames.push(newColor);
} else {
keepRunning = false;
}
}
// display color names entered
for (var i = 0; i < colorNames.length; i++) {
var cName = colorNames[i];
document.write(cName + " ");
}
//alert pop up based on number of inputs
if (keepRunning = false) {
if (i <= 4) {
alert('That's all you could think of? Refresh and try again!')
} else if (i <= 8) {
alert('Not bad, but you can probably do better. Refresh to play again.')
} else if (i <= 12) {
alert('Wow! You really know your colors! You can refresh to challenge yourself again!')
} else if (i >= 15) {
alert('I don't think anyone could do better than this, nice job!')
}
}
2
Answers
There’s two issues in your logic preventing it from working:
if (keepRunning = false)
condition=
needs to be==
or===
. A single=
is for assigning a value, not comparison of values.for
loop,i
is not accessible. You can fix the code, and make it more semantic, by usingcolorNames.length
in theif
conditions instead.In addition, there’s some general improvements you can make:
document.write()
. Either update the Elements in the DOM or create new ones. In the following example I create<p>
elements to display the text.keepRunning
will always befalse
, so there’s no point checking it in anotherif
statement.alert()
once.Here’s working example with the above amendments made:
There are two issues in your logic.