0

{data?.map((item, index) =>

How does the above line of code check for an empty array before mapping? I am not seeing any references for such. Any body please explain?

what does data? do?

Reference here: https://dev.to/madara/fetching-data-with-react-hooks-and-fetch-api-beginners-guide-2ick

4
  • 1
    It doesn't check for an empty array. If the array is empty the .map() method will just return an empty array in return, and the callback function won't be invoked. The data? checks that data isn't nullish (undefined / null) before calling .map() on it Commented Jun 20, 2021 at 7:36
  • @NickParsons data?.map - a question mark before .map does that? Commented Jun 20, 2021 at 7:39
  • 1
    The data? is optional chaining, if data is null/undefined, the .map() method isn't called at all, and your data?.map() evaluates to undefined. If data is empty, then .map() still gets called, but it just returns an empty array (and the callback doesn't get executed). Commented Jun 20, 2021 at 7:41
  • This is optional chaining. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 20, 2021 at 7:42

2 Answers 2

1

This is a condition, it check if the data exists befor map to avoid returning the error message "data is null" or "data is undefined".

data?.map((item, index) => { ... })

is the same as

data 
? data.map((item, index) => { ... }) 
: null

and the same as

if (data) 
data.map((item, index) => { ... })
Sign up to request clarification or add additional context in comments.

Comments

0

Adding ternary operator after data (data?) would check first that the data has a value and is not null or undefined, so it can not throw error in that case. It's a short hand for:

data ? data.map((item, index) => {}) : null

If the data has a value, it would execute map on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.