Site hosted by Angelfire.com: Build your free website today!
Website Help

| HTML | CSS | JavaScript |

Soon to come:
XHTML, XML, ASP,
Home

JS Basics

JS Home
Introduction
Basics
Operators
Functions
Conditional
Looping

JS References

String Object
Array Object
Date Object
Math Object
Window Object
Frame Object
Form Object
Browser Object

JavaScript Conditional


if and if...else

The if statement is one of the most common statements you will use. Here's the syntax:

     if (condition){
     [statement(s)]
     }
    

The condition can be any logical expression. the [statements] between the brackets { } will execute if the statement test out to be true.

If you want to execute a block of statements when the if statement is false, then you use the else statement.

     if(condition){
     [statement(s)]
     }
     else{
     [statement(s)]
     }
    

You can also put an if statement after else for the code to execute if the first statement is false and if this statement is true.

     if(condition){
     [statement(s)]
     }
     else if(condition){
     [statement(s)]
     }
     else{
     [statement(s)]
     }
     

switch

The Switch statement if you want to select one of many blocks of code to be executed.

     switch(expression)
     {
     case condition:
     code to be executed if condition is true
     break
     case condition:
     executed if this condition is true
     break
     ... as many case expressions...
     default:
     code executed if all cases evaluated to be false
     }
    

Each case will evaluate, if it is ture, the block of code will be executed, the break statement is to prevent further evaluation of the different variables. The default: statement at the end of the switch statement is required, if all cases evaluate to be false then the default block is activated.

Conditional Operator

There is also a way to assign a value to a variable based on a condition. The syntax is as follows...

     variable = (condition)? value1 : value2

eg:

     theDate = (today == "monday")? "true" : "false"
    

The first value, true will be stored to theDate if the expression (today == "monday") is true, while value2, false, will be stored to theDate if the expressions evaluates to be false

fastadvert.com


fastadvert.com - make money with your website