&&, ||, !
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 returnstrueorfalse.
Example
#const isLoggedIn = true
const fuel = 0
console.log(isLoggedIn && fuel > 0)
console.log(isLoggedIn || fuel > 0)
console.log(!isLoggedIn)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
#a && b
a || b
!a
!!a
a ||= b
a &&= bMore examples
#console.log('Emma' || 'Guest')
console.log('' || 'Guest')
console.log('Emma' && 'logged in')
console.log(0 && 'never')
console.log(!!'text', !!0)function loadAvatar() {
console.log('Fetching avatar...')
return 'avatar.png'
}
const cached = 'cache.png'
const avatar = cached || loadAvatar()
console.log(avatar)loadAvatar() was never called, because the left side of || was already truthy.
const player = { nickname: '', score: 40 }
player.nickname ||= 'Anonymous'
player.score &&= player.score * 2
console.log(player)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 replaces0,"", andfalse, which can be valid data. Use??in those cases. - In compound conditions, add parentheses even when precedence alone would be enough:
(isAdmin || isMentor) && isActivereads unambiguously. - In React,
{count && <Badge />}renders0whencountis zero. It’s safer to write{count > 0 && <Badge />}.
Related entries
#- ??The ?? (nullish coalescing) operator returns the right side only when the left side is null or undefined. Ideal for default values.
- ? :The conditional (ternary) operator returns one of two values depending on a condition, in one short expression.
- if...elseRuns a block of code only when the condition is true, and otherwise an optional else block.
- ===The strict equality operator compares values without type conversion: true only for the same type and the same value.
- ?.The ?. (optional chaining) operator safely reads a property. When the object is null or undefined, it returns undefined instead of throwing.
Spotted a mistake or missing an example? Write to us.