Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the question mark mean in the return statement in JS?

I've got a function service the using data from loader and transform it in the right way for me and then return new data I have a suggestion to use '?' before returning data in transformation that can make some sense if there will not be data from loader:


export default async function serviceInputSearch(url) {
  const data = await new DataLoader(url).get();
  return data?.data.results;
}

I cannot find any information in google about this '?' in return statement? What does it mean?

like image 780
Yaroslav Plyahtur Avatar asked Sep 09 '20 06:09

Yaroslav Plyahtur


People also ask

What does a question mark mean in a return statement?

But, given your example, the gist of it is that the question mark validates if there is a valid "data" object. If you do not have the question mark there and there is no data object or it is null, then an error will be thrown in the lines of "Cannot read the property data of 'undefined'".

What does the question mark mean in JS?

“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value.

What are the three uses of the question mark (?) In JavaScript?

Three Main Uses for the Question Mark ( ? ) in JavaScript: Optional Chaining. Nullish Coalescing.

What does double question mark mean in JS?

The JavaScript double question mark (??) operator is called the nullish coalescing operator and it provides a default value when a variable or an expression evaluates to null or undefined.


1 Answers

This is called optional chaining. You can find more information about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining.

But, given your example, the gist of it is that the question mark validates if there is a valid "data" object. If you do not have the question mark there and there is no data object or it is null, then an error will be thrown in the lines of "Cannot read the property data of 'undefined'".

like image 133
Leonardum Avatar answered Sep 28 '22 20:09

Leonardum