Optional Chaining
Optional chaining if extremely useful, it allows us to call a specific object key and if it’s undefined
or null
, it returns undefined
instead of throwing an error.
const res = await fetch('https://some.route/');
const json = await res.json();
if( json?.currentTemperature ){
// Your code...
}
Optional Chaining In PHP
$res = file_get_contents('https://some.route/');
$json = json_decode($res);
if( @$json?->currentTemperature ){
// Your code...
}
If you’re unsure what the @
is doing in this example I mention it in my article about Destructuring Assignment.