Course contentsShow
← JavaScript
Lesson 1943 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Optional Chaining vs. Logical AND

Compare obj?.prop with obj && obj.prop and understand when each pattern is appropriate.

Optional Chaining vs. Logical AND

What you'll learn: You'll understand the key differences between obj?.prop and obj && obj.prop, and when to choose each pattern.

The Two Patterns Compared

Before optional chaining existed, developers used the logical AND operator (&&) to safely access nested properties:

const name = user && user.profile && user.profile.name;

Now we have optional chaining:

const name = user?.profile?.name;

Both prevent errors when properties don't exist, but they behave differently in subtle ways.

Key Differences

1. What counts as "stop here":

  • && stops at any falsy value (0, "", false, null, undefined, NaN)
  • ?. only stops at null or undefined
const obj = { count: 0 };

console.log(obj && obj.count); // 0
console.log(obj?.count);        // 0

// But with falsy values:
const data = "";
console.log(data && data.length); // "" (stops at empty string)
console.log(data?.length);         // 0 (continues, empty string has length)

2. Clarity and intent:

  • ?. explicitly says "this might not exist"
  • && is a general logical operator that happens to work for existence checks

When to Use Each

Use optional chaining (?.) when:

  • You're checking if properties exist
  • You want to handle null/undefined specifically
  • Falsy values like 0 or "" are valid and shouldn't stop the chain

Use logical AND (&&) when:

  • You need actual boolean logic
  • You intentionally want to stop on any falsy value
  • You're checking conditions, not just existence

Key Takeaway: Optional chaining (?.) is purpose-built for safe property access and only cares about null/undefined, while logical AND (&&) treats all falsy values as reasons to stop—choose based on whether falsy values are valid in your context.