// Create an infinite loop, get user input, and write to screen
// Analysis

while(true)
	{
	fadeToR = prompt("Enter value for Red between 0 and 255 ('Quit' exits).", "0");
	if(fadeToR == null || fadeToR.toLowerCase() == "quit" || fadeToR > 255 || fadeToR < 0)
		break;
	fadeToG = prompt("Enter value for Green between 0 and 255 ('Quit' exits).", "0");
	if(fadeToG == null || fadeToG.toLowerCase() == "quit" || fadeToG > 255 || fadeToG < 0)
		break;
	fadeToB = prompt("Enter value for Blue between 0 and 255 ('Quit' exits).", "0");
	if(fadeToG == null || fadeToG.toLowerCase() == "quit" || fadeToB > 255 || fadeToB < 0)
		break;
	
	document.writeln(fadeToR + ", " + fadeToG + ", " + fadeToB + "<br>");
	}

This code prompts the user for three values, for red, green, blue values respectively, The return value of each prompt method is stored in its own variable, and written to the screen.

There are two important things to note about this example: the conditional must be executed in this order. An error will be produced if you try to compare a string to a number, so the checks for null and the "quit" string must go first. If either of those cases are true, the browser will execute the next statement (break;). If the value of the variable is a number, however, both of the equality tests will fail, and the relational operators will evaluate.

The other important detail is that the variable is converted to lower case using the toLowerCase() method in the equality test. This is done to ensure that the code will exit if the user types in any combination of upper and lower case letters to form the word 'quit'. Using the toLowerCase() method means that the code will respond appropriately to 'quit', 'Quit', 'QUIT', etc. Without this flexibility, the user could easily become confused or annoyed.

Close Window