JavaScript logical operators

If you’re accustomed to PHP’s logical operators, JavaScript’s implementation can be confusing.

PHP

In PHP, the rules are straightforward:

  • $a && $b returns true if both $a and $b are truthy
  • $a || $b returns true if either $a or $b are truthy

For example.

$a = true;
$b = 'truthy';
echo($a && $b);    // true

$c = null;
$d = true;
echo($c && $d);    // false

$e = 'truthy;
$f = false;
echo($e || $f);    // true

JavaScript

In JavaScript, life is more complex:

  • a && b returns b if a is truthy
  • a && b returns a if a is not truthy
  • a || b returns a if a is truthy
  • a || b returns b if a is not truthy

For example:

const a = true
const b = 'truthy'
console.log(a && b) // 'truthy'

const c = null
const d = true
console.log(c && d) // null

const d = 'truthy'
const e = null
console.log(d || e) // 'truthy'
console.log(e || d) // 'truthy'

In effect, JavaScript’s && and || operators behave like ternary operators.

// Same as 'a && b'
console.log(a ? b : a)

// Same as 'a || b'
console.log(a ? a : b)

Summary

The following table summarises the differences.

StatementJavaScriptPHP
true && 'truthy''truthy'true
null && 'truthy'nullfalse
’truthy’ || false'truthy'true
false || ‘truthy’'truthy'true

Sign up for my newsletter

A monthly round-up of blog posts, projects, and internet oddments.