Course contentsShow
← JavaScript
Lesson 309 of 2,7239. Control FlowFree lesson

Basic If Statement Syntax

Learn the fundamental if statement structure and how to execute code conditionally based on boolean expressions.

Basic If Statement Syntax

In this lesson, you'll learn how to write your first if statement to make decisions in your code.

What Is an If Statement?

An if statement lets your program make choices. Think of it like a bouncer at a club checking IDs: if someone meets the requirement (age 21+), they get in; otherwise, the code inside doesn't run.

The if statement evaluates a condition (a boolean expression) and only executes the code inside its block when that condition is truthy.

The Basic Structure

if (condition) {
  // code runs only if condition is truthy
}

Here's how it works:

  1. JavaScript evaluates the expression in parentheses
  2. If the result is truthy, the code block executes
  3. If the result is falsy, JavaScript skips the block entirely

Real Examples

let temperature = 75;

if (temperature > 70) {
  console.log("It's warm outside!");
}
// Output: "It's warm outside!"

if (temperature < 50) {
  console.log("Bring a jacket!");
}
// This doesn't run because 75 < 50 is false

The condition can be any expression that produces a value—comparison operators, logical operators, or even just a variable:

let isLoggedIn = true;

if (isLoggedIn) {
  console.log("Welcome back!");
}

Remember, JavaScript coerces the condition to a boolean using the rules you learned earlier.

Key Takeaway: The if statement executes a code block only when its condition evaluates to a truthy value, giving your programs the power to make decisions based on data.