3.3 If Else Statements

Purpose of Else Statements

Else statements: Handles what happens when the if condition is false. Structure of If-Else:

  • If statement with a condition.
  • Else statement without a condition.
  • Both parts have code blocks surrounded by {}.

don’t forget the brackets

if (x > 10) {

        console.log("x is greater than 10");
        console.log("This code when the condition is true");
    } else {
    
        console.log("x is 10 or less");
        console.log("This code runs when the condition is false");
    }
    Without brackets:
    
    if (x > 10)
    
        console.log("x is greater than 10");
        console.log("this code will always run");

image

  1. Based on this code, if you were younger than 16 what would it print out?
  2. Write your own if else statement

The code segment will print “You can learn to drive a car!”

//Hack - Dinesh Sahai
int myAge = 30;

System.out.println("Current Age:" + myAge);

if (myAge >= 35) {
    System.out.println("You can run for President!");
} else {
    System.out.println("You are too young too run for President! Try again when you are 35!");
}
Current Age:30
You are too young too run for President! Try again when you are 35!