1

I just saw this syntax in PHP:

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';

Why don't we have the same in JavaScript?

I am tired of doing:

var name = obj['name'] ? obj['name'] : 'GOD';
user94559
  • 59,196
  • 6
  • 103
  • 103
Ishwar Rimal
  • 1,071
  • 11
  • 19
  • P.S if we already have it, please let me know – Ishwar Rimal Aug 12 '17 at 05:08
  • 4
    `var name = obj['name'] || 'GOD';` – Pranav C Balan Aug 12 '17 at 05:08
  • You mean conditional operator. A ternary operator by definition takes three operands - that's what the word ternary means. You cannot have a ternary operator simpler than one that takes three operands - because an operator that takes two, such as the ?? shown here, is a binary operator, just like the arithmetic operators and the concat operator in PHP. – BoltClock Aug 12 '17 at 05:56

2 Answers2

5

The Null coalescing operator is a recent addition to PHP. It was introduced in PHP 7 (released in December 2015), more than 10 years after the feature was proposed for the first time.

In Javascript, the logical OR operator can be used for this purpose for ages (since Javascript was created?!).

As the documentation explains:

Logical OR (||)

expr1 || expr2

Returns expr1 if it can be converted to true; otherwise, returns expr2.
Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

Instead of writing

var name = obj['name'] ? obj['name'] : 'GOD';

you can use the shorter:

var name = obj['name'] || 'GOD';

The || operator can be used several times to create a longer expression that evaluates to the value of the first operand that is not empty:

var name = obj['name'] || obj['desc'] || 'GOD';
axiac
  • 68,258
  • 9
  • 99
  • 134
  • I am curious: How did you manage to post an answer 30 minutes after the question was closed? – Martin R Aug 12 '17 at 10:03
  • 1
    I don't know. I answered using the mobile app. Now I remember that after I posted the answer the question was loaded again and it was already closed. I thought at that time that it was closed right between my answer was posted and the question was reloaded but now I see that, indeed, the first version of my answer was posted 30 minutes after the question was closed. Maybe there is a glitch in the Matrix. :-) – axiac Aug 12 '17 at 10:15
2

In javascript you can do the following:

var name = obj['name'] || "GOD"

If the first value is false (null, false, 0, NaN, "" or undefined), then the second value is going to be assigned.

tiagodws
  • 1,345
  • 13
  • 20