2012-04-22 19:03:04Morris

[JavaScript] Conditionals in JavaScript

If else statements

var yourName = "Morris";
var gender = "male";
var result;

//Line 10 starts an if statement
//Nested in this if statement is an if else statement on lines 11 - 15
//This nested if else statement allows us to check another condition
//We close the first if statement at the start of line 16

if (yourName.length > 0 && gender.length > 0) {
  if (gender === "male" || gender === "female") {
    result = "Thanks";
  } else {
    result = "Please enter male or female for gender.";
  }
} else {
  result = "Please tell us both your name and gender.";
}


Using if else statements in functions

// Define the function under this line
var canIDrive = function(myAge, legalDrivingAge) {
    if(myAge >= legalDrivingAge)
        return true;
    return false;
}

// Declare legalDrivingAge under myAge
var myAge = prompt("How old are you?");

//Create an if else statement using the function as a condition
if (canIDrive(myAge, 18)) {
  console.log("You can legally drive!");
}
else {
  console.log("You'll have to wait a few more years!");
}


Introducing the Switch statement

var born = prompt("What country were you born in?");
var result;

// write the whole switch statement
switch(born) {
    case "USA":
        result = 1;
        break;
    case "England":
        result = 2;
        break;
    default:
        result = 3;
}


Ternary operators

var food = prompt("Food?");
var foodType;
if (food === "taco") {
  foodType = "Mexican";
} else {
  foodType = "other"; 
}

//Re-write the above code using a ternary operator
foodType = (food === "taco") ? "Mexican" : "other";