TechLead
Lesson 5 of 16

Conditionals

Choose different paths based on a condition.

Quick Summary

Conditionals run code only when a condition is truthy. JavaScript treats values like 0, "", null, undefined, and NaN as falsy, so understanding truthy/falsy helps avoid surprises.

Making Decisions in Code

Conditionals let your program make decisions and execute different code based on conditions.

if Statement

Execute code when a condition is true:

if (temperature > 30) {
  console.log("It's hot outside!");
}

if...else Statement

Handle both outcomes:

if (age >= 18) {
  console.log("You can vote");
} else {
  console.log("You cannot vote yet");
}

if...else if...else Chain

Handle multiple conditions:

if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else if (score >= 70) {
  grade = "C";
} else {
  grade = "F";
}

Truthy and Falsy Values

JavaScript evaluates any value as boolean in conditionals:

Falsy values (evaluate to false):

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

Truthy values (everything else):

  • true
  • Any non-zero number
  • Any non-empty string
  • Objects and arrays (even empty ones!)
if (username) {  // truthy if not empty
  console.log("Hello, " + username);
} else {
  console.log("Please log in");
}

Ternary Operator

Shorthand for simple if/else:

const status = age >= 18 ? "adult" : "minor";
const message = items.length > 0 ? "Items found" : "No items";

switch Statement

Handle many specific values:

switch (day) {
  case "Monday":
    console.log("Start of week");
    break;
  case "Friday":
    console.log("Almost weekend!");
    break;
  default:
    console.log("Regular day");
}

Try It Yourself

Here's a practical example you can try. Copy this code and run it in your browser's console (press F12 to open developer tools) or in the Code Playground.

// Basic if/else
const age = 20;
if (age >= 18) {
  console.log("You are an adult");
} else {
  console.log("You are a minor");
}

// Multiple conditions with else if
const score = 85;
let grade;
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else if (score >= 70) {
  grade = "C";
} else {
  grade = "F";
}
console.log("Your grade: " + grade); // "B"

// Truthy/falsy check
const username = "";
if (username) {
  console.log("Welcome, " + username);
} else {
  console.log("Please enter a username");
}

// Ternary operator (shorthand if/else)
const status = age >= 21 ? "Can drink" : "Cannot drink";

// Combining conditions with && and ||
const canDrive = age >= 16 && hasLicense;
const needsID = age < 21 || !hasMembership;

Key Takeaways

  • Choose different paths based on a condition.
  • Practice with real code examples to solidify your understanding
  • This concept builds the foundation for more advanced topics

Related Learning Resources

Continue your programming journey with these related tutorials: