Conditional Statements


There is basically one type of conditional statement, the if statement. The syntax is as follows:
 if (condition) {
   statement1;
   statement2;
   .
   statementN;
 }
[else {
   statement1;
   statement2;
   .
   statementN;
 }]
Example:
 if (variable == 1){
   DieChemistryDie();
 }
 else {
   Javascript = "Cool!";
 }
Basically it reads like English, "If the condition is true, execute the statements below [else execute these statements]." Note, the else part is optional.

Loops and whatnot....

In Javascript there are two basic types of loops that anyone cares about; for loops, and while loops. The syntax for each follows below:

 for ("variable initialization";"condition to continue loop";"variable increment expression";){
   statement1;
   statement2;
   .
   statementN;
 }
This should be pretty self-evident in how. If you're still confused, look at this example. It should clear it up.

 for (var i = 1; i <= 10; i++){
   variable1++
 }
This example basically adds a number to itself 10 times. On to the while loop!!

 while (condition){
   statement1;
   statement2;
   .
   statementN;
 }
This is probably the easiest of the loops. Basically while the condition is true it will execute the lines in the { }'s. Easy? Thought you would think so. Now here comes the more complicated stuff. What if you want to break out of a loop prematurely? Well guess what command you use? BREAK! Here's an example:

 function testBreak(x){ 
    var i = 0;
    while (i < 6) {
      if (i == 3) break;
      i++;
    }
    return i*x;
 }
The previous example basically terminates the while loop when i is 3, and then returns the value of 3 * x. Now what happens if you want to skip the rest of the loop; use continue ! Here an example with continue being used:

 i = 0;
 n = 0;
 while (i < 5) {
   i++;
   if (i == 3) continue;
   n += i;
 }
When the while loop is executing, when i equals 3, it will skip the line n += i; and continue on with the while loop. All other times it executes like normal.

There is one quick note that you might have noticed. If you have only one statement, you don't need the curly braces,{ }'s. While I'm on technicalities, I might as well mention that you don't need semicolons at the end of statements. The Javascript interpreter in will decide when a statement is complete. Granted it usually easier to see code with explicit endings of statements though.

Comments


Just a quick note on comments. They look just like C++ comments (Gee, kinda like the rest of JavaScript?)...
For a single line comment, use:
  // Every good boy and girl comments their code
For multi-line comments:
  /* This comment spans
  several lines... */

Return to the Front Page
Continue to the the next section: Objects