0

I normally use ternary operators like:

let foo = str.match(/[*]/g) ? str.match(/[*]/g) : "none!";

Since using PHP, I've noticed the language has a lot of shorthand and for ternary operators, would use:

$foo = $view->test ?? "none";

I have not seen that in javascript (or documentation on it) but tried it like:

let str = "1234";
let foo1 = str.match(/[*]/g) ?? "none;
console.log(foo) // "none"

let str1 = "1*2*";
let foo1 = str1.match(/[*]/g) ?? "none;
console.log(foo1) // ['*','*']

and it seemingly works. Is this an acceptable way of using ternary operators when checking against the existence of an element?

ddjk
  • 133
  • 2
  • 7
  • 4
    It's the [nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) – chazsolo Oct 13 '20 at 18:56
  • 2
    See the compatibility chart here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator#Browser_compatibility – Barmar Oct 13 '20 at 18:57
  • Does this answer your question? [Is there a "null coalescing" operator in JavaScript?](https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript) – chazsolo Oct 13 '20 at 18:58
  • 2
    This is *not* a ternary shortcut. If the first operand is `null` or `undefined` (vs. falsey value), the second operand is used. – crashmstr Oct 13 '20 at 18:59
  • doesn't the `||` operator already cover `null` and `undefined`, in addition to empty strings? – ddjk Oct 13 '20 at 19:00
  • FYI, usually you can search for those operators by writing it out. e.g. "js double question mark" should lead you to the nullish coalescing operator – A_A Oct 13 '20 at 19:02
  • 2
    @ddjk `||` covers any [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value. – Ivar Oct 13 '20 at 19:03
  • @ddjk Please accept correct answer , thanks ! – turbopasi Oct 20 '20 at 11:19

1 Answers1

1

I guess it's totally legit to use the nullish coalescing operator or ??. See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator for examples and some documentation on it.

Make sure to check browser compatibility though !

=======

There is also the logical OR || operator which can be used for similiar operations:

o1 = true  || true       // t || t returns true
o2 = false || true       // f || t returns true
o3 = true  || false      // t || f returns true
o4 = false || (3 == 4)   // f || f returns false
o5 = 'Cat' || 'Dog'      // t || t returns "Cat"
o6 = false || 'Cat'      // f || t returns "Cat"
o7 = 'Cat' || false      // t || f returns "Cat"
o8 = ''    || false      // f || f returns false
o9 = false || ''         // f || f returns ""
o10 = false || varObject // f || object returns varObject

Check out : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators for reference

turbopasi
  • 3,327
  • 2
  • 16
  • 43