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.
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.
// Every good boy and girl comments their codeFor multi-line comments:
/* This comment spans several lines... */