Return to Snippet

Revision: 1383
at October 3, 2006 05:08 by mlange


Initial Code
// -------------------------
//    switch

switch(myVar) {
  case 1:
    //if myVar is 1 this is executed
    break;
  case 'sample':
    //if myVar is 'sample' this is executed
    break;
  case false:
    //if myVar is false this is executed
    break;
  default:
    //if myVar does not satisfy any case, this is executed
	  //break; is unnecessary here as there are no cases following this
}

// -------------------------
//    with

x = Math.round( Math.LN2 + Math.E + Math.pow( y, 4 ) );
// replace by
with( Math ) {
  x = round( LN2 + E + pow( y, 4 ) );
}

// -------------------------
//    quick if

var myVariable = document.getElementById ? 1 : 0;


// -------------------------
//    try/catch/final

try {
  //do something that might cause an error
} catch( myError ) {
  //if an error occurs, this code will be run
  //two properties will (by default) be available on the
  //object passed to the statement
  alert( myError.name + ': ' + myError.message );
} finally {
  //optional - this code will always be run before the
  //control structure ends, even if you rethrow the error
  //in the catch
}

// -------------------------
//    throw

try{
  var myEr = new Object();
  myEr.name = 'My error';
  myEr.message = 'You did something I didn\'t like';
  throw( myEr );
} catch( detectedError ) {
  alert( detectedError.name + '\n' + detectedError.message );
}

// -------------------------
//    break to a label (best avoided)

myForLoop:
for( var x = 1; x < 5; x++ ) {
  var y = 1;
  while( y < 7 ) {
    y++;
    if( y == 5 ) { break myForLoop; }
    document.write(y);
  }
}

// -------------------------
//    continue

// Will cause the program to jump to the test condition of the structure // and re-evaluate it having performed any 'do_this_each_time' 
// instructions.

myForLoop:
for( var x = 1; x < 5; x++ ) {
  var y = 1;
  while( y < 7 ) {
    y++;
    if( y == 5 ) { continue myForLoop; }
    document.write(y);
  }
}

Initial URL
http://www.howtocreate.co.uk/tutorials/javascript/controls

Initial Description
Source: controls @ howtocreate

Initial Title
control structures

Initial Tags


Initial Language
JavaScript