0

So hear me out, I feel like there has to be a way, but I am really unsure.

Let's say I have this in my react project

{name ? name : "no name"}

but I am wondering if it were possible to somehow write this short to return the first value if true otherwise return the second value? something like this

{name ! "no name"} 

I feel like there has to be a way to do it, I am just curious if anyone knows how?

HAL9256
  • 12,384
  • 1
  • 34
  • 46
Nick H
  • 205
  • 2
  • 9

2 Answers2

3

Use the logical OR: ||

const name = '';
const test1 = name ? name : "no name";
const test2 = name || "no name";

console.log(test1, test2);

Documentation


For more info about ?? vs || please take a look at:

When should I use ?? (nullish coalescing) vs || (logical OR)?

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Thankyou! What is a better way to do this? nullish operator to the logical or? – Nick H Aug 27 '21 at 15:35
  • 1
    @NickH - See my comment on the other answer (where your comment asking this seems to have disappeared). – T.J. Crowder Aug 27 '21 at 15:37
  • @NickH That depends on what you would consider a valid value for the name: a "logical or" `||` would use the second value if the first one is *falsy* (`false`, `null`, `undefined`, `0`, `''`) while the "nullish coalescing" `??` would use the second value if the first one is... well *nullish* (either `null` or `undefined`). An empty string is falsy but not nullish, `0` is falsy but not nullish, etc... so you use one or the other, depending on whether you want to accept or not all falsy but not nullish values. – secan Aug 27 '21 at 15:41
2

You're looking for the nullish coalescing operator:

{ name ?? "no name" }
David
  • 208,112
  • 36
  • 198
  • 279
  • 2
    Or { name || "no name" }, in certain situations – iunfixit Aug 27 '21 at 15:34
  • 4
    @NickH - It depends on A) Does your target environment support nullish coalescing? (It's relatively new.) And B) Do you want **all** [falsy values](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) (`0`, `""`, etc.) to be skipped in favor of `"no name"` (use `||`) or just `null` and `undefined` (use `??`)? – T.J. Crowder Aug 27 '21 at 15:37