0

I have following code

getState(dc) {
  let state = data.channels[channelId]?.channelStatus.find(item => {
    item.dc === dc
  })
  return state;
}

in some cases i am getting channelStatus as [null] and throwing error cannot read property of null

How can i handle this in javascript?

5
  • 1
    channelStatus?.find Commented Jan 9, 2023 at 17:25
  • tried this,but its not working Commented Jan 9, 2023 at 17:28
  • Please show full error message Commented Jan 9, 2023 at 17:32
  • It's simple. Just copy and paste this: js function getState(dc) { let state = null; if (data) { if(data.channels) { if(data.channels[channelId]) { if(data.channels[channelId].channelStatus) { return data.channels[channelId]?.channelStatus.find(item =>{item.dc === dc}) } } } } } Commented Jan 9, 2023 at 17:37
  • 1
    What do you want to return for state when channelStatus is null? Commented Jan 9, 2023 at 17:46

1 Answer 1

2

What this function should return depends on what the calling code expects. Using optional chaining will prevent the code from throwing an error, but will instead return undefined, which may not be what the calling code expects.

You need to handle this by either returning a default value in case your first expression doesn't return anything, or changing the calling code so that it can appropriately deal with a return value such as undefined.

You can return a default value in case your first expression evaluates to undefined by using the nullish coalescing operator:

getState(dc) {
    const defaultValue = ''; // whatever your default value is
    return data.channels[channelId]?.channelStatus?.find(item =>{item.dc === dc}) ?? defaultValue;
}
Sign up to request clarification or add additional context in comments.

1 Comment

To add to this. Clean code is "liberal with what it will take, and conservative with what it will return". A sensible default like what AviusX described makes sense. I would only add that you should be more defensive with the data you access. You go three layers deep into an object without checking that any of those layers are shaped the way you expect. At the very least I would add some if blocks wrapping the find and make sure the layers exist before diving into them.

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.