Home > Back-end >  Getting error "Cannot read properties of undefined (reading 'sender') " once I p
Getting error "Cannot read properties of undefined (reading 'sender') " once I p

Time:07-08


export const isSameSender = (
  messages: any[],
  message: any,
  index: number,
  user: IUser
) => {
  return (
   //if I put just "<" instead of "<=" in the below line, there's no error
    index <= messages.length - 1 &&
    messages[index   1].sender._id === message.sender._id && //this line gives that error
    messages[index].sender._id !== user._id
  )
}

export const isLastMessage = (messages: any[], index: number, user: IUser) => {
  return index <= messages.length - 1 && messages[index].sender._id !== user._id
}

I feel if I haven't been able to understand && properly but why does puttting <= instead of < gives the error, I am trying to check if the messages array has reached it's final index to check if it has finished looping but as soon as I use <= in this code the second code gives the error, I don't know why.

Can anyone enlighten me on what's happening? If giving any[] as a type to the messages array is causing this problem?

CodePudding user response:

It's because if index is actually equal to messages.length - 1, then

messages[index 1] is undefined because messages[messages.length - 1 1] which means messages[messages.length], so undefined because there is not such index in the messages array.

  • Related