LILLY ROBOT |
Conditional statments are used for decision making. It is important to ensure the conditional statements are in the correct order when they are being executed.
In the if statement, if the condition is true then the statement inside the curly bracket is executed. You
can have more than one if statement.
if (condition)
{
statement to be executed if the condition is true;
}
Displays
In javascript document is an object and write() is a method. At this stage do not worry too much about objects and methods. Just familiarise yourself with document.write().
Any characters to be displayed on the screen must be placed inside a single or double quotation marks.
The + operator here is used as a concatenation (joins the strings).
Note: The html codes must be placed inside the quotation marks
("<h3>Hello!</h3>").
In the if...else statement if the condition is true the statement inside the first curly bracket is executed. Otherwise, the else curly bracket statement is executed.
if (condition)
{
statement to be executed if the condition is true;
}
else
{
statement to be executed if the condition is false;
}
Displays
In the if... else if... statement there are several conditions. If one of the condition is true the statement relating to that condition is executed. If none of the conditions are true then the else statemet 4
is executed.
if (condition)
{
statement 1 is executed if the condition is true;
}
else if
{
statement 2 is executed if the condition is true;
}
else if
{
statement 3 is executed if the condition is true;
}
else
{
statement 4 is executed if statement 1,2 and 3 are not true
}
Displays
In the switch statement there are several conditions. Each case condition is checked against the value of the variable. If it is true then the statement related to the case is executed. Otherwise, the default statement is executed.
switch (variable value)
{
case 1: Execute statement 1 if condition is true
break;
case 2: Execute statement 2 if condition is true
break;
default: Otherwise, excute statement 3
}
The break statement ends each case.
In the example below case number 1 has been selected.
Displays
If there was no break statement after case 1 then case 2 would also be executed. If there was no break statement at all, then case 1,2,3 and default would be excuted, one after the other.
Let us have a look what would be displayed if all the above breaks were removed and case 1 is selected
Displays