Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

Truthy and falsy decide if before you expect it

PHP’s if ($value) and JavaScript’s if (value) both test “is this value usable in a condition?” but JavaScript’s list of falsy values is longer and stricter comparisons (===) behave differently from loose ==.

PHP habit

<?php
if ('0') {
    echo "non-empty string is truthy\n";
}
if (0) {
    echo "never runs\n";
}
if ('') {
    echo "never runs\n";
}
if ([]) {
    echo "empty array is falsy in PHP\n";
}

// empty() is the explicit check many teams prefer
if (empty($name)) {
    echo "treat as missing\n";
}

JavaScript equivalent

if ('0') {
  console.log('non-empty string is truthy');
}
if (0) {
  console.log('never runs');
}
if ('') {
  console.log('never runs');
}
if ([]) {
  console.log('empty array is truthy in JS'); // runs!
}

// Explicit Boolean conversion when you mean it
if (Boolean(name)) {
  console.log('has a value');
}
Value PHP in if JavaScript in if
0 falsy falsy
'' falsy falsy
'0' truthy truthy
[] falsy truthy
null falsy falsy
undefined N/A falsy

Why this trips up == later

Loose equality coerces types using truthy rules. That is why 0 == false is true in JavaScript (and PHP). Strict === avoids that entire class of bugs.

<?php
var_dump(0 == false);   // true
var_dump(0 === false);  // false
console.log(0 == false);   // true
console.log(0 === false);  // false

Try it

Use the amber Try it panel below. Click Run.

const values = [0, '', '0', [], null, undefined, 'hello'];
for (const v of values) {
  console.log(JSON.stringify(v), 'truthy?', Boolean(v));
}

You should see [] and '0' as truthy. That is the mental shift before the equality lesson next.

From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs