Using the javascript or condition in JavaScript

A practical guide to the javascript or condition, exploring how || behaves with truthy/falsy values, default patterns, and common pitfalls.

JavaScripting
JavaScripting Team
·5 min read
Quick AnswerDefinition

JavaScript's or condition is implemented with the || operator, which returns the first truthy value it encounters and short-circuits the rest. This makes it ideal for providing default values and guard clauses in functions and UI logic. Mastering truthy/falsy semantics reduces bugs in everyday code. With practice, you can safely rely on || for concise fallbacks without sacrificing readability.

The javascript or condition in practice

In JavaScript, the javascript or condition is most often implemented with the || operator. It returns the first operand that is truthy and, if none are truthy, the last operand is returned. This behavior enables concise defaults and guards in a few lines of code. Below, we explore canonical patterns and how to reason about what gets returned in different scenarios.

JavaScript
// Basic OR usage: first truthy value wins const name = userName || 'Guest'; console.log(name); // 'Guest' if userName is falsy
JavaScript
// Short-circuit evaluation demonstrates minimal work function fetchName() { console.log('fetch'); return 'Alice'; } const who = undefined || fetchName(); console.log(who); // 'Alice' (fetch runs because left side is falsy)

How to read this: If the left operand is truthy, the right-hand side is never evaluated. This short-circuiting is central to understanding defaults with ||. Common variations include combining with other operators or using it inside function arguments.

linesCountedCodeBlocksForThisSectionCountedAsCodeExamplesInDescriptionToHelpEditorsOnlyForNow?FALSE?

exampleNoteTitleForCodeBlock?null

codeSnippets?null

Steps

Estimated time: 60-90 minutes

  1. 1

    Set up example code

    Create a small script or JS file with initial variables to experiment with the OR operator. Decide what you want to default (e.g., user name, GUI text).

    Tip: Start with a simple example to build intuition before adding complexity.
  2. 2

    Implement basic OR patterns

    Add lines that use || to provide defaults and observe the returned values in different scenarios (truthy vs falsy left operands).

    Tip: Use console.log to confirm what is returned for each case.
  3. 3

    Test with functions

    Create a function and pass its call on the right side of || to see when the function runs due to short-circuiting.

    Tip: Note when the function is not called because the left side is truthy.
  4. 4

    Contrast with nullish coalescing

    Add examples using ?? to preserve 0, '', and false where || would replace them.

    Tip: This helps you decide when to favor ?? over ||.
  5. 5

    Refactor for readability

    Wrap complex OR expressions in clearly named helpers or inline parentheses to improve readability.

    Tip: Avoid deeply nested or chained OR expressions.
  6. 6

    Apply to real code

    Replace ad-hoc defaults in a project with well-documented patterns and run tests to verify behavior.

    Tip: Document the chosen default strategy in code comments.
Pro Tip: Use parentheses to group complex OR expressions for clarity.
Warning: Beware that 0, '', and NaN are falsy and may trigger defaults unexpectedly.
Note: Consider nullish coalescing (??) when you need to preserve valid falsy values.
Pro Tip: Keep OR logic close to where you assign defaults to reduce cognitive load.

Prerequisites

Required

Optional

  • Familiarity with the console or DevTools
    Optional

Keyboard Shortcuts

ActionShortcut
Format codeIn VS Code or compatible editor+Alt+F
Toggle line commentComment/uncomment selected linesCtrl+/

Questions & Answers

What does the || operator return in JavaScript?

The || operator returns the first operand that is truthy. If all operands are falsy, it returns the last operand. It also short-circuits, meaning it stops evaluating once a truthy value is found.

|| returns the first truthy value and stops evaluating further operands.

Why can || be problematic for defaults?

Because many common values like 0, '', and NaN are falsy. Using || to provide defaults can override legitimate values, leading to bugs where a value you meant to keep is replaced.

Falsy values can unintentionally trigger defaults when using ||.

When should I use ?? instead of ||?

Use ?? when you want to default only on null or undefined, preserving valid falsy values like 0, ''. This is safer for numerical inputs and user-entered data.

Use ?? to preserve valid but falsy values.

Does || short-circuit function calls?

Yes. If the left-hand operand is truthy, the right-hand side is not evaluated, which can prevent unnecessary function calls.

|| short-circuits and may skip function calls.

Can I chain || with multiple conditions?

Yes. You can chain several || operators, but readability can suffer. Break complex expressions into helper functions or intermediate variables when needed.

Yes, but keep readability in mind.

Are there browser compatibility concerns?

All modern browsers support the || operator as part of JavaScript syntax. There are no special compatibility concerns for this operator.

Supported broadly across environments.

What to Remember

  • Understand || returns the first truthy value
  • Use || for concise defaults in UI and functions
  • Avoid relying on || when you need to preserve falsy values like 0 or ''
  • Prefer ?? for preserving null/undefined while keeping defaults elsewhere
  • Document the intended defaulting strategy for maintainability

Related Articles