The conditional operator performs a simple if-else test. The format of the statement is:
( condition ) ? exec_if_true : exec_if_false;
In this sample, you are prompted for your age and than that value is compared to the test if age is less than 18. An appropirate message is displayed based on your input. |
The if keyword is used to perform the basic conditional JavaScript test to evaluate an expression for a boolean value. The format is:
if(test)
{
statement(s);
}
In this example the prompt asks a user to enter a number. Based on the number entered one of two different conditional ifs are executed and display whether the number is odd or even. |
An if statement can be utilized along with a prompt to determine if the user entered a value or simply pressed the cancel button on the prompt message box. To test if the cancel button is clicked we use the null reserved word.
if(variable == null)
We can also test if no response is entered by using the second parameter of the prompt. By setting the parameter to an empty string we can than test for that input.
var valueEntered == prompt("Enter a value", "");
if(valueEntered == "")
In this example the prompt value is checked if nothing is entered or cancel is clicked by using a null value test. If the user enters their name than a customized welcome message is displayed. |
The JavaScript else keyword can be used with an if statement to provide alternative code to execute, in the event that the test expression returns false. You can test several expressions by adding or nesting another if as the statement to be executed in an if or else clause. The format of the if-else statement is:
if(condition)
{
statement(s);
}
else
{
statement(s);
}
In this example the user is prompted to enter a number between one and ten. The number is checked against a preset value and displays a message indicating whether the user's guess is higher, lower, or is the actual number. |
Conditional branching using the if-else statement may be more efficiently performed using a switch statement when a test expression evalutes the value of just one variable. The format of a Switch Statement is:
switch(variable)
{
case value:
statement(s);
break;
case value:
statement(s);
break;
...
default:
statement(s);
}
In this example the user is prompted to select a mood from a list. A message is displayed based on their mood. |
|