Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.
Safe defaults without throwing on nested data
PHP 7.4 gave you ??. PHP 8 gave you ?->. JavaScript has the same pair: ?? for nullish defaults and ?. for optional chaining. Together they replace long isset chains.
PHP habit: null coalescing
<?php
$user = null;
$name = $user ?? 'Guest';
$count = 0;
// || would be wrong if 0 is valid:
// $display = $count || 10;
$display = $count ?? 10; // 0 — only null/undefined trigger ?? in JS; in PHP ?? is null-only
Note: in PHP ?? only checks null (and undefined variable notices). In JavaScript ?? checks null and undefined.
JavaScript equivalent
const user = null;
const name = user ?? 'Guest';
const count = 0;
console.log(count || 10); // 10 — 0 is falsy
console.log(count ?? 10); // 0 — 0 is not nullish
| Expression | When right-hand side runs |
|---|---|
|| / && |
When left is falsy / truthy |
?? |
When left is null or undefined only |
PHP habit: nullsafe operator
<?php
$city = $user?->address?->city ?? 'Unknown';
JavaScript equivalent
const city = user?.address?.city ?? 'Unknown';
| PHP | JavaScript |
|---|---|
$user?->address |
user?.address |
?? 'Unknown' |
?? 'Unknown' |
Three forms of ?.
obj?.prop; // property
arr?.[0]; // index
callback?.(); // call only if function exists
Mapping from isset chains
<?php
$city = isset($user['address']['city'])
? $user['address']['city']
: 'Unknown';
const city = user?.address?.city ?? 'Unknown';
Shorter to read and no risk of notices when an intermediate key is missing.
Try it
Use the amber Try it panel below. Click Run.
const user = { address: { city: 'Leeds' } };
const missing = null;
console.log(user?.address?.city ?? 'Unknown');
console.log(missing?.address?.city ?? 'Unknown');
const count = 0;
console.log('with ||', count || 10);
console.log('with ??', count ?? 10);
You should see Leeds, then Unknown, then 10 and 0. That 0 line is why ?? matters for API and form defaults.
From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs