Today is:
    | Home | Web Technology | Language | Articles | | About-Us | Contact-Us |

JS Tutorial     

JavaScript Ch4 - Control Structures and Looping


4.1 Conditional Statements

If statement

The if is defined in the following way:

   if(condition){
      [statements]
   }
If the condition is true, the statements are executed.
Example 
If...else statement:
  if(condition){
     statements
  } else{
     statements
  }
Example 
for statement:
  for([initializing_expr];[condition_expr];[loop_expr]){
     statements
  }

The three expressions enclosed in parentheses are optional, but if you omit one, the semi-colons are still required. This keeps each expression in its appropriate place. You typically use the initializing expression to initialize and even declare a variable to use as a counter for the loop. Next, the condition expression must evaluate to true before each execution of the statements enclosed in curly braces. Finally, the loop expression typcially increments or decrements the variable that is used as the counter for the loop.

Example 
for ... in statement:
  for(property in object){
     statements
  }

property is a string literal gerated for you by JavaScript. For each loop, property is assigned the next property name contained in object until each one is used.

Example 
while statement:
  while(condition_expr){
     statements
  }

The while statement acts much like a for loop but doesn't include the function of initializing or incrementing variables in its declaration. You must declare variables beforehand and increment or decrement the variables within the statements.

Example 
break and continue statement:

A loop doesn't stop repeating itself until the specified condition returns false. However, you can exit the loop before the condition is met, by adding break to its statement block. You can also skip statements by adding continue before those statements to skip.

Example 
labeled statement:

The labeled statement can be placed before any control structure that can nest other statements. This lets you break out of the loop.

Example 
with statement:

The with statement is used to avoid repeatedly specifying the object reference when accessing properties or methods of that object. Any property or method in the with block that JavaScript doesn't recognize is associated with the object specified for that block. Here is the syntax:

with (object){
  statements
}
Example 
switch statement:

The switch statement is used to compare one value against many others.

Example 

    References

    (1) Aland Shalloway & James R. Trott, Design Patterns Explained, Second Edition.

    (2) Allen Holub, Holub on Patterns, Learning Design Patterns by Looking at Code

    (3) Eric Evans, Domain-Driven Design, Tackling complexity in the heart of software.

    Advertisement

puthik.com ©2008