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
returnstrue
if both$a
and$b
are truthy$a || $b
returnstrue
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
returnsb
ifa
is truthya && b
returnsa
ifa
is not truthya || b
returnsa
ifa
is truthya || b
returnsb
ifa
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.
Statement | JavaScript | PHP |
---|---|---|
true && 'truthy' | 'truthy' | true |
null && 'truthy' | null | false |
’truthy’ || false | 'truthy' | true |
false || ‘truthy’ | 'truthy' | true |
Sign up for my newsletter
A monthly round-up of blog posts, projects, and internet oddments.