Pete
Pete

Reputation: 3451

Trying to be concise in JavaScript with null coalescing and not figuring it out

I often write code like this after I retrieve a block of data, typically from a JSON server. I do it to check for either no data or bad data and then I don't have to check in all the code directly below it. My code always looks like this:

if (!(response && response.data && response.data.length > 0)) {
    return something nullish or whatever is appropriate
}

Is there a clean way with newer JavaScript to do this? I don't think changing &&'s to ||'s does the trick, but not sure.

Upvotes: 0

Views: 42

Answers (1)

Andrey
Andrey

Reputation: 76

I think Optional chaining can solve your problem.

response?.data?.length

Upvotes: 2

Related Questions