Conditionals

What are Conditionals?

  • Conditionals tests whether an “expression” evaluates to true or false and then makes a decision based on the results of that test

  • if statements are the most common form of conditionals

  • There are two types of if statements

    • (if..else) statements

    • (if..else if) statements


(if…else) statements

  • when evaluating between just two choices, use if/else

  • These are great for “either or” situations

  • You do not specify a condition for the “else” clause

    // if..else statement
    
    if (condition) {
    
      code to run if condition is true
    
    } else {
    
      code to run if the above condition is NOT true
    
    }
    
    run some other code
    
    

    Sometimes you’ll find that you don’t need an else clause. These are scenarios where you

    
    let brushedTeeth = false
    
    if(brushedTeeth){
    
      alert('Great job, you brushed your teeth!');
    
    } else {
    
      alert('Go your brush teeth man, your breath is hot right now!');
    }
    
    

    JS Bin on jsbin.com


(if…else if) statements

  • when evaluation among more than two choices, use if/else if

  • You must specify a condition on the “else if” clause

  • You can use as many else if clauses as you need

    // if..else if statement
    
    if (condition) {
    
      code to run if this condition is true
    
    } else if (another condition) {
    
      code to run if this condition is true
    
    } else {
    
      code to run if NONE of the above conditions are true
    }
    
    run some other code
    
    
    
    let yourGrade = 84;
    
    if (yourGrade >= 90) {
    
      alert("Congrats your score is 90 or above, that's an A!");
    
    } else if (yourGrade >= 80) {
    
      alert("Congrats your score is 80 or above, you earned a B");
    
    } else {
    
      alert("Your score is less than 80, no bueno");
    
    }
    
    

    JS Bin on jsbin.com