&&, ||, !

The logical operators AND (&&), OR (||), and NOT (!). They combine conditions, and && and || return one of their sides.

Returns
&& and || return the value of one of their sides (not necessarily a boolean). ! always returns true or false.
On this page

Example

#
JavaScript
const isLoggedIn = true
const fuel = 0

console.log(isLoggedIn && fuel > 0)
console.log(isLoggedIn || fuel > 0)
console.log(!isLoggedIn)
Console
false
true
false

Definition and usage

#

&& (and) is true when both sides are true, || (or) when at least one is true, and ! (not) flips a boolean value. You combine them most often in if conditions, e.g. if (isLoggedIn && hasFuel).

&& and || don’t always return true or false, just one of their sides. a || b returns a if it’s truthy, and otherwise b. a && b returns a if it’s falsy, and otherwise b. Doubling it up, !!value, converts any value into true or false.

Both operators take shortcuts: the right side isn’t evaluated once the result is already known from the left. That’s why user && user.name doesn’t throw for null. && has higher precedence than ||, and the operators ||= and &&= assign a value only under the matching condition.

Syntax

#
Syntax
a && b
a || b
!a
!!a
a ||= b
a &&= b

More examples

#
The operators return values
JavaScript
console.log('Emma' || 'Guest')
console.log('' || 'Guest')
console.log('Emma' && 'logged in')
console.log(0 && 'never')
console.log(!!'text', !!0)
Console
Emma
Guest
logged in
0
true false
Short-circuit evaluation
JavaScript
function loadAvatar() {
  console.log('Fetching avatar...')
  return 'avatar.png'
}

const cached = 'cache.png'
const avatar = cached || loadAvatar()

console.log(avatar)
Console
cache.png

loadAvatar() was never called, because the left side of || was already truthy.

The ||= and &&= assignments
JavaScript
const player = { nickname: '', score: 40 }

player.nickname ||= 'Anonymous'
player.score &&= player.score * 2

console.log(player)
Console
{ nickname: 'Anonymous', score: 80 }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Watch out for || with default values. It also replaces 0, "", and false, which can be valid data. Use ?? in those cases.
  • In compound conditions, add parentheses even when precedence alone would be enough: (isAdmin || isMentor) && isActive reads unambiguously.
  • In React, {count && <Badge />} renders 0 when count is zero. It’s safer to write {count > 0 && <Badge />}.

Related entries

#

Spotted a mistake or missing an example? Write to us.