VirtualMV/JavaScript/Starting/Controlling flow

From WikiEducator
Jump to: navigation, search




Introduction

Overview

A programmer is asked by their partner to "go to the dairy and get a loaf of bread. If they have eggs, get a dozen." The programmer come home with 12 loaves of bread.


VmvIcon Objectives.png

By the end of this page you will be able to:

Controlling the flow - making decisions

Javascript decision functions are very similar to those used in C++

The three comonly used decision functions are:

  • if {…..}
  • if {……} else {…..}
  • switch

if

if (condition){
   code to be executed if condition is true
}

if .... else

if (condition){
  code to be executed if condition is true
}
else {
  code to be executed if condition is false
}

Example (js1_09)

<html>
<body>
<script type="text/javascript">
var datDate = new Date();
var vntTime = datDate.getHours();
if (vntTime < 12) {
  document.write("Time =" + vntTime + " <b>Good morning</b>")
  }
else {
  document.write("Time =" + vntTime + " <b>Good afternoon</b>")};  
</script>
<p>This example demonstrates the If statement.</p>
<p>If the time on your browser is less than 12, you will get a "Good morning" greeting.</p>
<p> otherwise you will get a good afternoon</p>
</body>
</html>

Example :Click here to run js1_09.

switch

switch(n){
  case 1:
    execute code block 1
    break; // prevents code running into the next case
  case 2:
    execute code block 2    
    break; 
  default:
    code to be executed if n is different from case 1 and 2 
}

Example (js1_10)

<script type="text/javascript">
/* You will receive a different greeting based on
   what day it is. Note that Sunday=0, Monday=1,
   Tuesday=2, etc.*/
  var datDate=new Date();
  datDay=datDate.getDay();
  switch (datDay){
    case 1:
      document.write("Drat it’s Monday");
      break;  
    case 2:
      document.write("Only Tuesday");
      break; 
      // remainder of the code
    default:  document.write("I'm looking forward to this \
            weekend!")};
</script>

Example :Click here to run js1_10.


VmvIcon References.png References

virtualMV  |  Superquick wiki guide  |  Please give me some feedback

VirtualMV/JavaScript/Starting/Controlling flow. (2024). In WikiEducator/VirtualMV wiki. Retrieved November 21, 2024, from http:https://wikieducator.org/VirtualMV/JavaScript/Starting/Controlling_flow    (zotero)