JavaScript uses the basic statements found in most languages.
if/then/else
if (condition) { statement block 1; } else { statement block 2; }
do while
do { statement block; } while (expression);
while
while (expression) { statement block; } <h2>for</h2> [code lang="javascript"] for (initialization; expression; post-loop-expression) { statement block; } //example for (var x=1; x<10; x++) { //do something } console.log(i); //note that i is valid outside the loop because there are no block-level variables.
for-in
Used to iterate the properties of an object.
for (property in expression) { statement block; }
break
Used in a loop to exit the loop immediately and continue at the statement following the loop.
continue
Used in a loop to exit the loop but executes from the beginning of the loop. This basically just exits this iteration of the loop and starts the next iteration, whereas the break statement exits the loop completely.
Labeled statements
Statements can have labels and are used with the break and continue to indicate how far they break out of nested loops.
mylabel: for (x=1; x < 10; x++) { for (y=1; y< 10; y++) { if (x == y) break mylabel; } }
In this example, the break will exit both for loops because the label mylabel
is outside both loops.
with
The with
statement allows you to use a block of statements on an object without typing the object name everytime.
var x = myobject.toString(); var y = myobject.replace(' ', '', mystring); // can be replaced with: with myobject { var x = toString(); var y = replace(' ', '', mystring); }
switch
This works the same as for most languages. Don’t forget to put the break
statement at the end of each case
or the next case
statements will be executed too. No conversion are done on the elements before they are used in the conditions.
switch (x) { case '1': // this can be an expression such as case x < 10; statement block; break; //omitting this will allow the code in the next block to be executed after this block. case '2': statement block; break; default: statement block; }