The Differences in Truthiness and Falsiness in JavaScript vs PHP

Conditionals that check whether a value is true or false are a fundermental part of building any software, whether that is a website or a desktop application. When working across different programming languages, understanding how they handle truthiness and falsiness is crucial for writing reliable code. JavaScript and PHP, two of the most widely used languages in web development, handle these values and their checks differently. Let's explore these differences and their practical implications. JavaScript's Approach to Truthiness The biggest difference between how JavaScript handles truthiness and falsiness compared to PHP is how it treats empty arrays and objects. Before we look at how it does that, let us look at some fundamentals. JavaScript treats the following values as false: const value1 = false // Boolean false const value2 = 0 // Number zero const value3 = "" // Empty string const value4 = null // null const value5 = undefined // undefined const value6 = NaN // Not a Number This includes their refs in frameworks like Vue.js: const ref1 = ref(false) const ref2 = ref(0) const ref3 = ref("") const ref4 = ref(null) const ref5 = ref(undefined) const ref6 = ref(NaN) Confusingly, the following values and their ref equivalents are truthy: const value7 = [] // Empty array const value8 = {} // Empty object const value9 = "0" // String containing "0" Why is this the case? It Has To Do With Memory In JavaScript, empty arrays and objects are considered "truthy" because they are valid object references. This is a fundamental aspect of JavaScript's type system and how it handles truthiness. // Arrays and Objects are references to memory locations // Even when empty, they are still valid references const emptyArray = [] // Points to a valid array in memory const emptyObject = {} // Points to a valid object in memory // When converted to boolean, any valid reference is true Boolean([]) // true Boolean({}) // true // Compare this with actual falsy values Boolean(0) // false Boolean("") // false Boolean(null) // false Boolean(undefined) // false This is Deliberate This design choice was made because: An empty array/object is still a valid data structure that you can add items to Empty arrays and empty objects are reference types (pointing to locations in memory) rather than primitive values Having a reference, even to an empty container, is different from having nothing (null/undefined) PHP's Different Perspective PHP takes a more intuitive approach for many developers, treating empty data structures as falsy values. To reiterate, empty arrays and empty objects are actually considered "falsy" in PHP and this one of the key differences between PHP and JavaScript. Here's how it works: // Empty array is falsy $emptyArray = []; if (!$emptyArray) { echo "Empty array is false"; // This will print } // Empty object is also falsy $emptyObject = new stdClass(); if (!$emptyObject) { echo "Empty object is false"; // This will print } // All these are also falsy in PHP: $false = false; // Boolean false $zero = 0; // Integer 0 $zeroFloat = 0.0; // Float 0.0 $empty = ""; // Empty string $null = null; // null $emptyArray = []; // Empty array Checking for Truthiness and Falsiness in Empty Arrays and Objects in JavaScript If you need to check truthiness and falsiness in JavaScript for these data types, you have to use the appropriate methods: //For an array [].length === 0 // true - explicitly checking emptiness //For an object Object.keys({}).length === 0 // true - explicitly checking emptiness To do the same with refs: const arrayRef = ref([]); const objectRef = ref({}); // Correct way to check emptiness if (arrayRef.value.length === 0) { console.log('Array is empty'); } if (Object.keys(objectRef.value).length === 0) { console.log('Object is empty'); } Checking for Truthiness and Falsiness in Empty Arrays and Objects in PHP PHP's intuitive approach to checking truthiness and falsiness comes in handy for developers. Here's how it works: // Empty data structures are falsy in PHP $emptyArray = []; $emptyObject = new stdClass(); if (!$emptyArray) { echo "This will execute because empty arrays are falsy\n"; } if (!$emptyObject) { echo "This will execute because empty objects are falsy\n"; } About PHP's empty() Many developers use empty() to check for truthiness and falsiness, even for empty arrays and objects. The PHP empty() function is a built-in function that checks if a variable is considered empty. Here's how it works: // All these will return true with empty() empty(""); // Empty string empty(0); // Zero as integer empty(0.0); // Zero as float empty("0"); // String "0" empty(null); // null emp

Jan 18, 2025 - 11:55
The Differences in Truthiness and Falsiness in JavaScript vs PHP

Conditionals that check whether a value is true or false are a fundermental part of building any software, whether that is a website or a desktop application.

When working across different programming languages, understanding how they handle truthiness and falsiness is crucial for writing reliable code.

JavaScript and PHP, two of the most widely used languages in web development, handle these values and their checks differently. Let's explore these differences and their practical implications.

JavaScript's Approach to Truthiness

The biggest difference between how JavaScript handles truthiness and falsiness compared to PHP is how it treats empty arrays and objects.

Before we look at how it does that, let us look at some fundamentals.

JavaScript treats the following values as false:

const value1 = false     // Boolean false
const value2 = 0         // Number zero
const value3 = ""        // Empty string
const value4 = null      // null
const value5 = undefined // undefined
const value6 = NaN       // Not a Number

This includes their refs in frameworks like Vue.js:

const ref1 = ref(false)
const ref2 = ref(0)
const ref3 = ref("")
const ref4 = ref(null)
const ref5 = ref(undefined)
const ref6 = ref(NaN)

Confusingly, the following values and their ref equivalents are truthy:

const value7 = []        // Empty array
const value8 = {}        // Empty object
const value9 = "0"       // String containing "0"

Why is this the case?

It Has To Do With Memory

In JavaScript, empty arrays and objects are considered "truthy" because they are valid object references.

This is a fundamental aspect of JavaScript's type system and how it handles truthiness.

// Arrays and Objects are references to memory locations
// Even when empty, they are still valid references
const emptyArray = []    // Points to a valid array in memory
const emptyObject = {}   // Points to a valid object in memory

// When converted to boolean, any valid reference is true
Boolean([])  // true
Boolean({})  // true

// Compare this with actual falsy values
Boolean(0)         // false
Boolean("")        // false
Boolean(null)      // false
Boolean(undefined) // false

This is Deliberate

This design choice was made because:

  1. An empty array/object is still a valid data structure that you can add items to
  2. Empty arrays and empty objects are reference types (pointing to locations in memory) rather than primitive values
  3. Having a reference, even to an empty container, is different from having nothing (null/undefined)

PHP's Different Perspective

PHP takes a more intuitive approach for many developers, treating empty data structures as falsy values.

To reiterate, empty arrays and empty objects are actually considered "falsy" in PHP and this one of the key differences between PHP and JavaScript.

Here's how it works:

// Empty array is falsy
$emptyArray = [];
if (!$emptyArray) {
    echo "Empty array is false"; // This will print
}

// Empty object is also falsy
$emptyObject = new stdClass();
if (!$emptyObject) {
    echo "Empty object is false"; // This will print
}

// All these are also falsy in PHP:
$false = false;     // Boolean false
$zero = 0;         // Integer 0
$zeroFloat = 0.0;  // Float 0.0
$empty = "";       // Empty string
$null = null;      // null
$emptyArray = [];  // Empty array

Checking for Truthiness and Falsiness in Empty Arrays and Objects in JavaScript

If you need to check truthiness and falsiness in JavaScript for these data types, you have to use the appropriate methods:

//For an array
[].length === 0              // true - explicitly checking emptiness

//For an object
Object.keys({}).length === 0 // true - explicitly checking emptiness

To do the same with refs:

const arrayRef = ref([]);
const objectRef = ref({});

// Correct way to check emptiness
if (arrayRef.value.length === 0) {
    console.log('Array is empty');
}

if (Object.keys(objectRef.value).length === 0) {
    console.log('Object is empty');
}

Checking for Truthiness and Falsiness in Empty Arrays and Objects in PHP

PHP's intuitive approach to checking truthiness and falsiness comes in handy for developers. Here's how it works:

// Empty data structures are falsy in PHP
$emptyArray = [];
$emptyObject = new stdClass();

if (!$emptyArray) {
    echo "This will execute because empty arrays are falsy\n";
}

if (!$emptyObject) {
    echo "This will execute because empty objects are falsy\n";
}

About PHP's empty()

Many developers use empty() to check for truthiness and falsiness, even for empty arrays and objects.

The PHP empty() function is a built-in function that checks if a variable is considered empty. Here's how it works:

// All these will return true with empty()
empty("");        // Empty string
empty(0);        // Zero as integer
empty(0.0);      // Zero as float
empty("0");      // String "0"
empty(null);     // null
empty(false);    // Boolean false
empty([]);       // Empty array
empty(new stdClass()); // Empty object
empty($undefined_var); // Undefined variable

// Examples of non-empty values
empty("0.0");     // false - string containing "0.0"
empty("string");  // false - non-empty string
empty(true);      // false - boolean true
empty(42);        // false - non-zero number
empty([0]);       // false - array with element


// PHP's empty() function is very versatile
$various_values = [
    "",        // empty string
    0,         // zero
    "0",       // string zero
    null,      // null
    false,     // boolean false
    [],        // empty array
    new stdClass() // empty object
];

foreach ($various_values as $value) {
    if (empty($value)) {
        echo "Value is considered empty in PHP\n";
    }
}

The key advantage of empty() is that it's safe to use on undefined variables. It does not trigger a warning like using isset() might (see below for explanation and example code). This makes it particularly useful in form handling:

// Safe form input checking
if (empty($_POST['username'])) {
    echo "Please enter a username";
}

// Checking object properties
$user = new stdClass();
if (empty($user->name)) {
    echo "Name is required";
}

It's worth noting that empty() is a language construct, not a function, which means you can't use it as a callback or variable function.

Here's an example showing why empty() can't be used as a callback or variable function, unlike regular PHP functions:

// This works with regular functions
$callback = 'strlen';
echo $callback("test");  // Works fine: outputs 4

// This will NOT work with empty()
$checker = 'empty';
$value = [];
echo $checker($value);   // Error: Call to undefined function empty()

// This also won't work in array_filter
$values = ["", "test", 0, 1, [], [1,2]];

// This will NOT work
array_filter($values, 'empty');    // Error

// Instead, you need to use a closure/anonymous function
array_filter($values, function($value) {
    return empty($value);
});

// Or with arrow function syntax (PHP 7.4+)
array_filter($values, fn($value) => empty($value));

Again, empty() is a language construct (like isset() or unset()), similar to operators or control structures, rather than a regular function.

When isset() Triggers a Warning

In PHP, isset() is a function used to determine if a variable is set and is not null.

isset() returns true if the variable exists and has a value other than null; otherwise, it returns false.

It does not trigger an error for undefined variables but can produce warnings when used on non-array types with array keys. This commonly happens when trying to use array keys with an uninitialized variable.

For example:

// Example: Triggering a warning with isset()
$data = null;

// Trying to check isset() on an undefined array key
if (isset($data['key'])) {
    echo "Key exists.";
} else {
    echo "Key does not exist.";
}

In this example

  • $data is null in this case, so it’s not an array.
  • Using $data['key'] triggers a warning because you’re attempting to access an index on a variable that is not an array.

If you do this, you will receive a warning like this:

Warning: Trying to access array offset on value of type null
Key does not exist.

To avoid this, you can add a type check before using isset():


$data = null;

if (is_array($data) && isset($data['key'])) {
    echo "Key exists.";
} else {
    echo "Key does not exist.";
}
?>

This helps you avoid the warning because is_array() verifies $data is an array before trying to access the key.

Practical Implications

These differences in how JavaScript and PHP handle empty arrays and objects, as well as truthiness and falsiness have significant implications for code design and debugging:

  • In JavaScript, you need to be explicit about checking for empty collections, which can make code more verbose but also more precise.
  • PHP's approach can make conditional logic simpler, but might require additional checks when you need to distinguish between different types of empty values.
  • When converting code between the two languages, these differences often require special attention to maintain the intended behavior.

Consider this common scenario:

// JavaScript - checking for empty data
function processData(data) {
    if (!data) {
        // This won't catch empty arrays or objects
        return 'No data provided';
    }
    if (Array.isArray(data) && data.length === 0) {
        return 'Empty array provided';
    }
    // Process data...
}
// PHP - checking for empty data
function processData($data) {
    if (empty($data)) {
        // This will catch empty arrays and objects
        return 'No data provided';
    }
    // Process data...
}

Understanding these fundamental differences is crucial for developer working with JavaScript and PHP, for example those using Laravel with React or Vue.

Doing so will help you write more reliable cross-platform code and avoid common pitfalls when switching between languages.

I hope this clears the confusion in using truthy and falsy valye in JavaScript and PHP. Have a question or comment? Feel free to elave it below. It would also eman the world to me if you shared this post here and on social media.

See you in the comment section!