2

I want to understand if my use case will benefit from the logical nullish assignment operator.

I'm checking my database to see it some data exists, otherwise I fetch it from an API, however I don't want to fetch the data from the API if the data already exists in my database, I'm describing the scenario with some code below.

let myData = await Database.getData(); // will return null if the data doesn't exist
myData ??= await fetch("API"); // does this API call get executed even if myData is non null?

Just to clarify, I'm wondering if the API call is executed, even though it might return the database data.

Does using nullish coalescing instead make a difference, for such a scenario ?

I'm aware that I can use several methods including if-else for such a case, however I want to understand if these operators will for in such a scenario.

rishi
  • 652
  • 1
  • 6
  • 20

2 Answers2

2

does this API call get executed even if myData is non-null?

No, it will not be executed.

myData ??= await fetch("API")

is equivalent to

myData ?? (myData = await fetch("API"))

So, only if the first expression myData is nullish, the second assignment part runs.

let value = "test"
value ??= null.toString() // doesn't throw error because it is not executed
console.log(value)

value = null
value ??= null.toString() // throws error
adiga
  • 34,372
  • 9
  • 61
  • 83
0

The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

The answer is no. details

dev_mustafa
  • 1,042
  • 1
  • 4
  • 14
  • Thanks for your answer, although my question was directed in terms of whether the righ-hand-side operand runs, even though it might return the left hand side. This was clarified by @adiga s answer. i.e. No it doesn't run. Also, it seems the link is broken, I'm unable to open it. – rishi Jan 19 '23 at 07:17
  • updated the link. Great that you got your answer you can visit the link to understand the details of the operator. – dev_mustafa Jan 19 '23 at 07:37