Search code examples
javascripttypeerror

Typescript type errors don't happen sometimes in my "for..in..." code


There was no problem when testing, but sometimes the error "Cannot read properties of null (reading 'nickname')" occurs. I took some of my code.

let seat = [
  null,
  null,
  { nickname: "user1", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" },
  null,
  { nickname: "user2", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" },
  null,
  null,
  null,
  null,
  null,
  null,
];
for (const i in seat) {
  if (seat[i].nickname === "user1") {
    seat[i] = null;
    break;
  }
}

console.log(seat);

I don't know why sometimes there is no problem and suddenly an error occurs.

for (const i in seat) {
  if (seat[i] !== null && seat[i].nickname === "user1") {
    seat[i] = null;
    break;
  }
}

I temporarily solved the problem by changing the code in the form above. I'm curious about the cause...


Solution

  • That's because some of the elements in the array are null values, So you should add a condition to check that as you did seat[i] !== null but you can use the Optional chaining operator ?. as well.

    FYR https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

    for (const i in seat) {
      if (seat[I]?.nickname === "user1") {
        seat[i] = null;
        break;
      }
    }
    

    Ex: If you have the data something like the one below, you don't need to add the condition or the optional chaining operator.

    let seat = [
      { nickname: "user1", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" },
      { nickname: "user4", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe263" },
      { nickname: "user5", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe264" },
      { nickname: "user3", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe265" },
      { nickname: "user1", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe267" },
      { nickname: "user2", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe269" },
    ];
    for (const i in seat) {
      if (seat[i].nickname === "user1") {
        seat[i] = null;
        break;
      }
    }