RPeraltaJr
4/23/2017 - 1:52 AM

JavaScript Ternary Operator (Shorthand If/Else Statement)

JavaScript Ternary Operator (Shorthand If/Else Statement)

// {condition} ? {expression if true} : {expression if false}
let biggerNumber = num1 > num2 ? num1 : num2

// * EXAMPLE ONE:
let y = (x == 2 ? "yes" : "no"); // if x == 2 then 'yes', else 'no'

// * EXAMPLE TWO:
const openDropdown = () => {
  
    // LONG VERSION
    // if ( dropdown.hasClass('active') ) {
    //     dropdown.removeClass('active');
    // } else {
    //     dropdown.addClass('active');
    // }
    
    // SHORT VERSION
    dropdown.hasClass('active') ? dropdown.removeClass('active') : dropdown.addClass('active');
}