-3

I found this pieces of code: Here, What is the ?. JavaScript operator? And Will I be able to use ?? Nullish Coalescing Operator in JavaScript instead of || OR operator according to the mentioned code snippet below?

const location = {
  lat: data?.coords?.latitude,
  long: data?.coords?.longitude
}
const docId = auth.currentUser?.uid || '123'
  • Technically you should be using `??` instead of `||`, as there is a chance `uid` may return a falsy value that is neither null nor undefined: `const docId = auth.currentUser?.uid ?? '123'` – Terry Aug 12 '20 at 11:41
  • @ViduminiKulathunga It's the [optional chaining operator](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Optional_chaining) – D. Pardal Aug 12 '20 at 11:43
  • 1
    Does this answer your question? [What is the obj?.prop syntax in javascript?](https://stackoverflow.com/questions/54528778/what-is-the-obj-prop-syntax-in-javascript) – Sebastian Simon Aug 15 '20 at 03:22
  • 1
    See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) and [statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Aug 15 '20 at 03:23

1 Answers1

4

It's a bit unclear what you're asking. This code:

const location = {
  lat: data?.coords?.latitude,
  long: data?.coords?.longitude
}

assigns undefined to lat if either data or data.coords is null or undefined (rather than throwing an error). But if data and data.coords are both not null or undefined, it assigns data.coords.latitude and data.coords.longitude to lat and long. It's the new optional chaining operator.

The next line also uses it, but:

  1. If the uid could be a falsy value (like "" or 0), you should use the new nullish coalescing operator as well: ?? rather than ||.

  2. If auth may be null or undefined, you need another ?.

So:

const docId = auth?.currentUser?.uid ?? '123'
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • That's neat, since when JS allows a *null-conditional* operator like in C# ? Is that new or have I missed this since a lot of time ? – Cid Aug 12 '20 at 11:47
  • @Cid https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript – mplungjan Aug 12 '20 at 11:53