04

Conditional Code

Chapter 4 • Beginner

30 min

Conditional Code

Conditional statements allow your program to make decisions and execute different code based on different conditions.

if Statements

The most basic conditional statement:

javascript.js
if (condition) {
    // code to execute if condition is true
}

if-else Statements

Execute different code based on whether a condition is true or false:

javascript.js
if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

if-else if-else Statements

Handle multiple conditions:

javascript.js
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}

Truthy and Falsy Values

In JavaScript, all values are either "truthy" or "falsy" when evaluated in a boolean context.

Falsy Values

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

Truthy Values

Everything else is truthy, including:

  • Non-zero numbers
  • Non-empty strings
  • Objects
  • Arrays (even empty ones)

Ternary Operator

A shorthand way to write simple if-else statements:

javascript.js
let message = (age >= 18) ? 'adult' : 'minor';

Switch Statements

Use switch statements when you have many conditions to check:

javascript.js
switch (dayOfWeek) {
    case 'Monday':
        console.log('Start of work week');
        break;
    case 'Friday':
        console.log('TGIF!');
        break;
    default:
        console.log('Regular day');
        break;
}

Hands-on Examples

if-else Statement

let age = 20;
let message;

if (age >= 18) {
    message = 'You are an adult';
} else {
    message = 'You are a minor';
}

console.log(message);

The if-else statement checks if age is 18 or greater and assigns the appropriate message.