JavaScript Logical Operators

Combine Conditions

JavaScript Logical Operators

`&&`, `||`, and `!` combine conditions. They also have a useful short-circuit behavior you'll see everywhere in real code.

5 min read Level 2/5 #logical#and#or
What you'll learn
  • Combine conditions with `&&` (AND) and `||` (OR)
  • Negate a condition with `!` (NOT)
  • Understand short-circuit evaluation

JavaScript has three logical operators:

OperatorNameReads as
&&ANDboth true
``
!NOTflip the value
The basics script.js
const age = 21;
const hasLicense = true;

console.log(age >= 18 && hasLicense);   // true  (both true)
console.log(age >= 18 || hasLicense);   // true  (either true)
console.log(!hasLicense);               // false (flip)
▶ Preview: console

Short-Circuit Evaluation

&& and || don’t always evaluate the right side. They short-circuit as soon as the answer is decided.

  • a && b returns a if it’s falsy; otherwise b.
  • a || b returns a if it’s truthy; otherwise b.
They return values, not just booleans script.js
console.log("hello" && "world");  // "world"   ← first is truthy, return second
console.log("" && "world");       // ""         ← first is falsy, return it
console.log("" || "fallback");    // "fallback" ← first is falsy, return second
console.log("hi" || "fallback");  // "hi"       ← first is truthy, return it
▶ Preview: console

Defaults With ||

The most common use: provide a fallback when a value is missing.

Defaults with || script.js
function greet(name) {
  const safe = name || "friend";
  console.log(`Hello, ${safe}!`);
}

greet("Ada");      // "Hello, Ada!"
greet("");         // "Hello, friend!"
greet(undefined);  // "Hello, friend!"
▶ Preview: console

Guarding With &&

Use && to do something only when a precondition holds.

Guard with && script.js
const user = { name: "Ada", isAdmin: true };

user.isAdmin && console.log("Show admin panel");
// Logs only if isAdmin is true.
▶ Preview: console

This pattern is common in JSX/React for “render this conditionally”.

Precedence

! binds tighter than &&, which binds tighter than ||.

Mixing operators script.js
const a = true;
const b = false;
const c = true;

console.log(a && b || c);     // true   ← (a && b) || c
console.log(a || b && c);     // true   ← a || (b && c)
console.log(!a && b);         // false  ← (!a) && b
▶ Preview: console

A Note on Boolean Conversion

!value is the cleanest way to negate. !!value converts to a real boolean.

Double-bang trick script.js
console.log(!!"hello");   // true
console.log(!!"");        // false
console.log(!!0);         // false
console.log(!!{});        // true  ← objects are truthy
▶ Preview: console

Up Next

|| falls back on too many things. ?? is more precise.

JavaScript Nullish Coalescing →