Javascript Data Structure Tutorial - Javascript Decision Statement








Decision statements such as if and switch allow the programs to make decisions on statements to execute based on a Boolean expression.

Javascript has the if statement. We can use them to execute statements by a boolean value.

The if statement comes in three forms:

  • The simple if statement
  • The if-else statement
  • The if-else if statement




Example for a simple if statement

The following code shows how to write a simple if statement.


var mid = -1; 
var high = 50; 
var low = 1; 
var current = 13; 
var found = -1; 
/*from w w  w  . j  av a2s .  com*/
console.log(mid);
if (current < mid) { 
    mid = (current-low) / 2; 
    console.log(mid);
} 




Example for if-else statement

The following code demonstrates the if-else statement.


var mid = 25; 
var high = 50; 
var low = 1; 
var current = 13; 
var found = -1; 
/*  www.java2s.c om*/
console.log(mid);
if (current < mid) { 
    mid = (current-low) / 2; 
    console.log(mid);
} else { 
    mid = (current+high) / 2; 
    console.log(mid);
} 

Example for if-else if statement

The following code illustrates the if-else if statement.


var mid = 25; 
var high = 50; 
var low = 1; 
var current = 13; 
var found = -1; 
//  w w  w  .j  a v a 2 s.  c  o  m
console.log(mid);
if (current < mid) { 
    mid = (current-low) / 2; 
    console.log(mid);
} 
else if (current > mid) { 
    mid = (current+high) / 2; 
    console.log(mid);
} 
else { 
    found = current; 
    console.log(found);
} 
console.log("over");

Switch Statement

The switch statement provides a cleaner, more structured construction when you have several simple decisions to make.

The following code demonstrates how the switch statement works.


var monthNum = 1; 
var monthName; 
switch (monthNum) { //from w w w. j a  v a2s. c om
    case "1": monthName = "January"; 
              break; 
    case "2": monthName = "February"; 
              break; 
    case "3": monthName = "March"; 
              break; 
    case "4": monthName = "April"; 
              break; 
    case "5": monthName = "May"; 
              break; 
    case "6": monthName = "June"; 
              break; 
    case "7": monthName = "July"; 
              break; 
    case "8": monthName = "August"; 
              break; 
    case "9": monthName = "September"; 
              break; 
    case "10":monthName = "October"; 
              break; 
    case "11":monthName = "November"; 
              break; 
    case "12":monthName = "December"; 
              break; 
    default: console.log("Bad input"); 
} 

console.log(monthName);