Conditionals
Programming Languages · JavaScript Basics · 12 min
Let your code make decisions with comparisons, if / else and the ternary.
True or false?
A comparison asks a question and answers true or false (a boolean). > < >= <= compare sizes. === asks "exactly equal?" and !== asks "not equal?".
JavaScript also has ==, which converts types first, so 5 == "5" is true. That causes sneaky bugs, so always use ===.
Print
age >= 18.Print
5 == "5"and then5 === "5"to see the difference.
if and else
if runs a block of code only when its condition is true. else runs when it's false. The block lives between { }.
if (isRaining) {
console.log("Take an umbrella");
} else {
console.log("Enjoy the sun");
}
If
temperatureis greater than25, printHot day. Otherwise printNice day.
More choices: else if
else if adds another check between if and else. JavaScript tries each condition from the top and runs the first one that's true, then skips the rest.
if (speed > 100) {
console.log("Fast");
} else if (speed > 50) {
console.log("Medium");
} else {
console.log("Slow");
}
Print
Aifscoreis 90 or more,Bif it's 70 or more, andCotherwise.
And, or, not
Combine conditions:
&&(and):trueonly if both sides are true.||(or):trueif at least one side is true.!(not): flipstruetofalseand back.
if (hungry && hasFood) {
console.log("Eat!");
}
If
hasTicketis true andageis 18 or more, printWelcome in.If
isWeekendorisHolidayis true, printSleep in.Print
!isWeekend.
The ternary: a one-line if
When you just need to pick between two values, the ternary is a shortcut: condition ? valueIfTrue : valueIfFalse.
let hour = 9;
const greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(greeting); // Good morning
Create
labelwith a ternary:"even"ifn % 2 === 0, otherwise"odd".Print
label.
Put it together: ticket booth
Kids under 13 pay 5, everyone else pays 10. Kids and students get a discount ticket. Use a ternary for the price and if / else with || for the ticket type.
Create
pricewith a ternary:5ifage < 13, otherwise10.If
age < 13orisStudent, printDiscount ticket. Otherwise printFull ticket.Print
Price:followed byprice, likePrice: 5.
More in JavaScript Basics
Previous: Strings and Numbers · Next: Functions