Will the Logical nullish Assignment or nullish coalescing evaluate the assigned value in a non null case?

224 views Asked by At

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.

2

There are 2 answers

0
adiga On BEST ANSWER

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

2
dev_mustafa On

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