Conditional Statements in JavaScript


The if statement

if (a == 1) window.alert ("Found a 1!");
	
if (a == 1)
{
	window.alert ("Found a 1!");
	a = 0;
}

Conditional operators

Logical operators

... this ...
if (phone == " ") window.alert ("error");
if (email == " ") window.alert ("error");
... becomes ...
if (phone == " " || email = " ") window.alert ("error");

The conditional expression

variable = (condition) ? if true : if false;

value = (a == 1 ) : 1 : 0;

if (a == 1)
	value = 1;
else
	value = 0;

The shortened version of the conditional if statement above value = (a == 1 ) : 1 : 0; can be embedded in other statements.

document.write ("Found " + counter + ((counter == 1) ? " word." : "words."));

Testing of multiple conditions with the switch statement

switch (button)
{
	case "next" :
		window.location = "next.html";
		break;
	case "previous" :
		window.location = "previous.html";
		break;
	case "home" :
		window.location = "home.html";
		break;
	case "back" :
		window.location = "menu.html";
		break;
	default :
		window.alert ("Wrong button");;
}