CourtneyJordan
5/21/2015 - 12:37 PM

If ... Else Statements

If ... Else Statements

##Switch

specify many alternative blocks of code to be executed

The getDay() method returns the weekday as a number between 0 and 6. (Sunday=0, Monday=1, Tuesday=2 ..)

switch (new Date().getDay()){
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
}

###If

specify a block of code to be executed, if a specified condition is true

Output String if 5 is less than 10

//if 5 is less than 10
if(5 < 10){
  //output to console
  console.log("5 is less than 10");
}

###Else

specify a block of code to be executed, if the same condition is false

If the hour is less than 16, create a "Good day" greeting, otherwise "Good evening":

//
if(hour < 16){
  //output to console
  greeting = "Good Day!";
}else{
  //output to console
  greeting = "Good Night!";
}
greeting();

###Else if

specify a new condition to test, if the first condition is false

If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening"

//if time is less than 10
if (time < 10) {
  //output that it's morning 
  greeting = "Good morning";
//if time is less than 20
} else if (time < 20) {
  //output that it's afternoon
  greeting = "Good day";
} else {
  //output that it's night  
  greeting = "Good evening";
}