Software, Systems, and Solutions

"We do not run your business. We make your business run better."

Skip Repetitive Navigational Links

JavaScript: Statements


  • JavaScript statements should end in a ;.
  • A statement is any  "complete sentence" of JavaScript code, that causes some program action to occur.
  • var dog;    // a variable declaration
  • dog = window.prompt('Enter an Integer', '0');
               // a method call
               // function associated w/ object
  • parseInt(dog); // a function call

JavaScript: Control Structures


  • Branching or 
  • Selection Repetition/Iteration

Selection: "if" Statement

 
<script language="JavaScript"> 
  var temp=prompt('Enter a temperature');
  if (temp < 35) 
  {  document.write('<h1>It's cold!</h1>'); }
</script>
  • If the expression in the parenthesis is true, the statements inside the brackets will be executed. If the expression is not true, the code will be skipped.
  • If there is more than one line to be executed in the code block, that code must be enclosed in brackets {    }.      (See example below)

Selection: Nested if Statements

  • if statements can be written within other if statements, which are called nested if statements:
if (expression1) // expression to be evaluated
{ // start code block
    statement1;
    if (expression2) // nested expression
    { // start nested code block
      statement2;
    } // end nested code block
} // end code block
  • In this example, if expression1 is true statement1 will be executed, then expression2 will be evaluated. If expression2 is also true, then statement2 will be executed. If expression1 is false, then the entire code block will be skipped.

Selection: "if/else" Statement

  • if-else statements are used when two blocks of code could potentially be executed – the first block if expressionA is true, and the second block if expressionA is false.
<script language="JavaScript"> 
if (expressionA)
// block executed if true
   statementA1;
   statementA2;
}
else  // optional
// block executed if false
   statementB;
}
</script>
<script language="JavaScript"> 
 var t=prompt('Enter a temperature (F)');
 if (t < 35) 
 {  
   document.write('<h1>'+ t +' is cold!</h1>'); 
 }
 else
 {  
   if (t > 90) 
     document.write('<h1>'+ t +' is hot!</h1>'); 
 }
</script>

What would the page say if 95 was entered?_____________ 70?__________ 35?_____________


Selection: if/else if" Statement

  • if-else if statements are used when multiple blocks of code could potentially be executed – the first block if expressionA is true, and the second block if expressionB is true, etc. and the else block if all the expressions are false.
<head>
<script language="JavaScript"> 
   if (expressionA) 
      statement1; 
   else if(expressionB) 
   {   
       statement2;
       statement3;
   }
   . . .
   else if (expressionN) 
      statementN; 
   else
      default_statement;
</script>
</head>
<script language="JavaScript"> 
  var t=prompt('Enter a temperature (F)');
  if (t < 35) {
    document.write('<h1>'+t+' is cold!</h1>'); 
  }
  else if (t < 60) {
    document.write('<h1>'+t+' is chilly!</h1>'); 
  }
  else if (temp < 90) {
    document.write('<h1>'+t+' is warm!</h1>'); 
  }
  else {
    document.write('<h1>'+t+' is hot!</h1>'); 
  }
</script>

What would the page say if 95 was entered? ____________ 70?___________ 35?______________.


if-else if Example

  • One use if/else if on a Web page is to customize the greeting:
<SCRIPT LANGUAGE="JavaScript"> <!--  
   var today = new Date (); Get current Date/Time
   var hrs = today.getHours(); Get hours for Date
   document.writeln("<CENTER><BR><H2>"); 
   if (hrs > 5 && hrs < 12) 
      document.write ("Good Morning"); 
   else if (hrs >= 12 && hrs <= 18) 
      document.write ("Good Afternoon"); 
   else if (hrs >= 18 && hrs <= 23)
      document.write ("Good Evening");
   else
      document.write ("What are you doing up?");
   document.writeln("</h2></CENTER><br>");
//--> </SCRIPT>

Selection: "switch" Statement

  • Provides an alternative to the if-else-if statement. A variable is matched to multiple cases, each having its own block of code:
<script language="JavaScript"> 
switch (switch_variable)
{
   case const1: note the colon 
     statement1;
     statement2;
    break; break is necessary or statement3 will be executed
   case const2
     statement3;
    break;
   . . .
   default:  default_statements;
}</script>
    <script language="JavaScript">
      var mc=prompt("Enter Marital Status (M,S,D,W)");
      switch(mc)
      {
        case 'M':
          document.write("<p>You are married.</p>");
          break;
        case 'S':
          document.write("<p>You are single.</p>");
          break;
        case'D':
          document.write("<p>You are divorced.</p>");
          break;
        case 'W':
          document.write("<p>You are widowed.</p>");
          break;
        default:
          document.write("<p>Invalid code.</p>");
      }
    </script>

    Repetition/Iteration: while & do while

    • while:  if the expression in the parenthesis is true, the code inside the brackets is executed. If it is false, the code is skipped (pretest loop).
    • do-while: the block of code is executed then the expression is evaluated to see if the block of code should be executed again.
    while ( condition )
      statement; 

    do
    {

      statement1;
      statement2;
    }while ( condition );

    Repetition/Iteration: for statements:

    • for: repeats a series of statements a particular number of times. 
    for ( initialization; condition; increment)
       statement;

    // or

    for ( initialization; condition; increment)

       statement1;
       statement2;
       statement3;
    }
    <script language="JavaScript"> 
      var result = 0, c;
      document.write('<h1>while result');
      do 
      {
         c = prompt('Enter a # (0 to Exit):');
         result = result + c; 
      } while (c > 0);
      document.write(' = ' + result +'<br>');
      
      result = 0;
      document.write('<br>for result');
      for (var i=0; i < 10; i++)
      {
          c = prompt('Enter a #:');
         result = result + c;
      }
      document.write(' = ' + result +'<br></h1>');
    </script>

    Control Structures: break/continue


    • break, continue statements:
      • break will jump completely out of a loop or out of the switch statement as above.
      • continue will jump from current position back to the loop statement (statement2 would be skipped):
    while (...){
      if (...) 
         statement1;
      else continue;
      statement2;
    }
    • No GoTo statement in JavaScript.

    Comments


    • JavaScript has 2 ways to indicate comments in the code:
      • //- 2 forward slashes indicates a single line comment

    x = 5;  // Set the value of x

      • /*  */  - bracket the comment with /* and */
    /*
     * Popular to use a column 
     * of asterisks to indicate 
     * a comment block
     */
    • Good Programming Practice: Always comment every major block of code (if block, for loop or a function) to indicate what the purpose of that block of code is:

    // Loop to get grades and sum them

    or

    /* Select the correct message for a given 
       temperature input (t) */


    Developing and Debugging Code


    Design

    • Programs follow algorithms, step-by-step processes for solving a problem
    • Designs specify the algorithms and data needed
      • They establish the objects, methods & functions required
    • Details of algorithms may be expressed in pseudocode, an English description of an algorithm (code-like w/o specific syntax)
    • Make a flowchart or pseudocode description of your algorithm FIRST.

    Why Design & Requirements Analysis is Important

    • Preplanning what needs to be accomplished in a program and the logic of how it is to be carried out:
      • reduces development times
      • reduces logic errors
      • allows better code to be developed
    • Pseudocode -- Make a detailed description of your algorithm's logic before worrying about specific language syntax and data layout.
    • Flowchart -- A graphical layout of the algorithm is often very useful in spotting "illogical" logic!

    Implementation

    • Implementation is the process of translating a design into source code
    • Most novice programmers think that writing code is the heart of software development, but it actually should be the least creative
    • Almost all important decisions are made during requirements analysis and design
    • Implementation should focus on coding details, including style guidelines and documentation

    Testing

    • A program should be executed multiple times with various input in an attempt to find errors.
    • Debugging is the process of discovering the cause of a problem and fixing it.
    • Programmers often erroneously think that there is "only one more bug" to fix
    • Tests should focus on design details as well as overall requirements