VirtualMV/JavaScript/Starting/Controlling flow

From WikiEducator
Jump to: navigation, search



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 (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)

<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>")};  
<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>

Example :Click here to run js1_09.


  case 1:
    execute code block 1
    break; // prevents code running into the next case
  case 2:
    execute code block 2    
    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();
  switch (datDay){
    case 1:
      document.write("Drat it’s Monday");
    case 2:
      document.write("Only Tuesday");
      // remainder of the code
    default:  document.write("I'm looking forward to this \

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. (2022). In WikiEducator/VirtualMV wiki. Retrieved August 12, 2022, from http:    (zotero)