2
$client = [
  'info' => [
    'company' => 'Apple',
  ]
];

echo $client['information']['company'] ?? 'N/A';

The above PHP code will show N/A as output, quietly. While the following Javascript will throw a Uncaught TypeError:

var user = JSON.parse(' { "info" : { "company" : "apple" } } ');

console.log(user.information.company ?? 'N/A');

Is there a similar ?? operation in Javascript which can show the N/A result quietly?

ohho
  • 50,879
  • 75
  • 256
  • 383
  • 3
    You could use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) with null coalescing which has a similar behaviour e.g. you'd do `user?.information?.company ?? 'N/A'` – apokryfos Dec 19 '20 at 10:39

1 Answers1

3

In Javascript ?? refer to Nullish coalescing operator That returns its right-hand side operand when its left-hand side operand is null or undefined.

user.information.company will return Uncaught TypeError: Cannot read property 'company' of undefined Error instead.

Better to use The optional chaining operator (?.) in this case, that permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

Sample :

var user = JSON.parse(' { "info" : { "company" : "apple" } } ');
console.log(user?.information?.company ?? 'N/A');
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101