CodeMIRAI
0 XP

if, else and the ternary

2 min read 5 runnable examples Quiz included

if, else if, else

JavaScript
const hour = 15;

if (hour < 12) {
  console.log("Good morning");
} else if (hour < 18) {
  console.log("Good afternoon");
} else {
  console.log("Good evening");
}

The condition goes in round brackets and the block in curly braces. Only the first true branch runs.

Comparison operators

OperatorMeaning
=== / !==strictly equal / not equal
< > <= >=less / greater (or equal)

Logical operators

OperatorMeaning
&&and: both must be true
||or: at least one true
!not
JavaScript
const age = 20;
const hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log("Welcome to the show");
}
if (!hasTicket || age < 18) {
  console.log("Sorry, you can't enter");
}

Truthy and falsy

Any value can be used as a condition. These are falsy: false, 0, "", null, undefined, NaN. Everything else is truthy, including "0", [] and {}.

JavaScript
const username = "";
if (username) {
  console.log("Hello, " + username);
} else {
  console.log("Please enter a name");
}

The ternary operator

condition ? valueIfTrue : valueIfFalse chooses between two values in one expression:

JavaScript
const stock = 0;
const label = stock > 0 ? "In stock" : "Sold out";
console.log(label);

const n = 7;
console.log(`${n} is ${n % 2 === 0 ? "even" : "odd"}`);

Default values with ?? and ||

JavaScript
const settings = { theme: null, fontSize: 0 };
console.log(settings.theme ?? "light");     // ?? only replaces null/undefined
console.log(settings.fontSize ?? 16);       // keeps 0
console.log(settings.fontSize || 16);       // || replaces any falsy value, even 0
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.