Tuesday, 15 February 2011

Javascript: Loops and Conditional Statements

Hi Everyone,

This is the 3rd installment of the Javascript series. Here, we will look at loops and conditional statements for Javascript.

Loops

The coding below shows how a Javascript for loop looks like:


var count = 10;
for (var i=0; i < count; i++)
{
    // statements
}


This will loop from i = 0 until i = 9. The counter, which is i, will increment after each loop (notice i++).  i++ can be changed to i-- if the counter starts from a high number and then incrementally decreasing.

Another loop will be the while loop as shown below. The statements in the while loop will be performed while the condition is true or being met.


while (condition)
{
   // statements
}


Conditional Statements

We can also perform conditional statements using Javascript. The most common one will be the if...else and the if...else if...else statements.


if (condition)
{

}

else
{

}



or 


if (condition)
{

}

else if (condition)
{


}
else
{


}


If there are more conditions, then the if...else statement should be used. The else statement will be perform the required coding if any of the conditions is not met. It is the default action to be performed. 

If there is only one condition to check, then if the condition is not met, it will immediately performs the action in the else statement.

Another conditional statement will be the switch statement. If there are a lot of conditions to check, the switch statement is the alternative way of the if...else statements. It will look simplified and improves the performance of Javascript programming. 

The syntax is as below:


switch (condition)
{
       case value1:
             statement
             break;


       case value2:
            statement
            break;
       case value3: value4:...
            statement
            break;
       default:
            // break
}


The first line will indicate which condition will be checked. Then, the case statements will indicate the possible values that we need to check. There can be multiple values for a case as indicated in case value3: value4:. It is neater if there are a lot of values to be checked.


That's all for today. 

Please feel free to comment or indicate if there are any mistakes I made. Learning does not end. It is a continuous process. I may have a lot of experience in Javascript (nearly 4 years now) but I may not know everything about Javascript because I may not use them.

Cheers,

Rogerkoo

No comments:

Post a Comment