Conditionals (if-else & switch)

🟨 JavaScript Lesson 5 Beginner

Conditionals control program execution flow using boolean assertions. JavaScript supports if-else checks, switch statements, and ternary evaluations.

1 Truthy & Falsy Evaluations

In conditional statements, JavaScript coerces non-boolean variables into boolean values. Values that evaluate to `false` are called **falsy**: `false`, `0`, `""` (empty string), `null`, `undefined`, and `NaN` (Not-a-Number). **All other values are truthy** (including empty arrays `[]` and empty objects `{}`).

2 Logical Flows & Switch Conditionals

Let's run a program evaluating conditions and checking truthy structures:

JavaScript — Conditionals ▶ Run Code
let score = 75;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 70) {
    console.log("Grade: B");
} else {
    console.log("Grade: F");
}

// Truthy vs Falsy
let username = ""; // Falsy
if (username) {
    console.log("User is logged in.");
} else {
    console.log("Guest mode active."); // Prints because string is empty
}

// Ternary execution
let val = 10;
let classification = (val % 2 === 0) ? "Even" : "Odd";
console.log("Number is " + classification);
3 Code Challenge
Challenge: Write a conditional statement that tests if an array is empty (e.g. checking `array.length`). Print out a message. Verify why checking an array directly in an `if (arr)` block is a trap since empty arrays are truthy in JavaScript.