control structures


/ Published in: JavaScript
Save to your folder(s)

Source: controls @ howtocreate


Copy this code and paste it in your HTML
  1. // -------------------------
  2. // switch
  3.  
  4. switch(myVar) {
  5. case 1:
  6. //if myVar is 1 this is executed
  7. break;
  8. case 'sample':
  9. //if myVar is 'sample' this is executed
  10. break;
  11. case false:
  12. //if myVar is false this is executed
  13. break;
  14. default:
  15. //if myVar does not satisfy any case, this is executed
  16. //break; is unnecessary here as there are no cases following this
  17. }
  18.  
  19. // -------------------------
  20. // with
  21.  
  22. x = Math.round( Math.LN2 + Math.E + Math.pow( y, 4 ) );
  23. // replace by
  24. with( Math ) {
  25. x = round( LN2 + E + pow( y, 4 ) );
  26. }
  27.  
  28. // -------------------------
  29. // quick if
  30.  
  31. var myVariable = document.getElementById ? 1 : 0;
  32.  
  33.  
  34. // -------------------------
  35. // try/catch/final
  36.  
  37. try {
  38. //do something that might cause an error
  39. } catch( myError ) {
  40. //if an error occurs, this code will be run
  41. //two properties will (by default) be available on the
  42. //object passed to the statement
  43. alert( myError.name + ': ' + myError.message );
  44. } finally {
  45. //optional - this code will always be run before the
  46. //control structure ends, even if you rethrow the error
  47. //in the catch
  48. }
  49.  
  50. // -------------------------
  51. // throw
  52.  
  53. try{
  54. var myEr = new Object();
  55. myEr.name = 'My error';
  56. myEr.message = 'You did something I didn\'t like';
  57. throw( myEr );
  58. } catch( detectedError ) {
  59. alert( detectedError.name + '\n' + detectedError.message );
  60. }
  61.  
  62. // -------------------------
  63. // break to a label (best avoided)
  64.  
  65. myForLoop:
  66. for( var x = 1; x < 5; x++ ) {
  67. var y = 1;
  68. while( y < 7 ) {
  69. y++;
  70. if( y == 5 ) { break myForLoop; }
  71. document.write(y);
  72. }
  73. }
  74.  
  75. // -------------------------
  76. // continue
  77.  
  78. // Will cause the program to jump to the test condition of the structure // and re-evaluate it having performed any 'do_this_each_time'
  79. // instructions.
  80.  
  81. myForLoop:
  82. for( var x = 1; x < 5; x++ ) {
  83. var y = 1;
  84. while( y < 7 ) {
  85. y++;
  86. if( y == 5 ) { continue myForLoop; }
  87. document.write(y);
  88. }
  89. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.