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

Implicit Blocks vs Explicit Braces

Understand the difference between single-statement if blocks and explicit braces, and why braces are preferred.

Implicit Blocks vs Explicit Braces

You'll learn when you can skip braces in if statements and why you usually shouldn't.

Single-Statement Shortcut

JavaScript allows you to write an if statement without curly braces {} if the block contains only one statement:

if (isLoggedIn)
  console.log("Welcome!");

This is called an implicit block or braceless syntax. The single statement immediately following the condition is executed if the condition is true.

Why Braces Are Preferred

While implicit blocks are valid JavaScript, they create maintenance problems. Imagine you need to add a second line later:

// Dangerous! Only the first line is conditional
if (isLoggedIn)
  console.log("Welcome!");
  showDashboard();  // This ALWAYS runs!

Without braces, only the first statement belongs to the if. The indentation tricks your eye, but JavaScript ignores it. The second line runs unconditionally—a classic bug.

Always Use Explicit Braces

The safer, clearer approach is explicit braces:

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

Now adding statements is safe:

if (isLoggedIn) {
  console.log("Welcome!");
  showDashboard();  // Both lines are conditional
}

The Real-World Impact

Think of braces like seatbelts: you might not need them for a short trip, but they prevent disasters when things change. Code evolves constantly—someone (often you, months later) will add lines without noticing the missing braces.

Key Takeaway: While JavaScript permits single-statement if blocks without braces, always use explicit braces {} for consistency, safety, and future-proof code.