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.
No, it will not be executed.
is equivalent to
So, only if the first expression
myData
is nullish, the second assignment part runs.