본문 바로가기
카테고리 없음

01. Cannot read properties of undefined (reading 'length')

by woody-j 2023. 5. 23.

Cannot read properties of undefined (reading 'length') 

TypeError: Cannot read properties of undefined (reading 'length')

 

이 오류 메시지는 정의되지 않은 값의 length 속성에 접근하려고 해서 발생하는 오류입니다. 
이 문제를 해결하기 위해서는 사용하기 전에 접근하려는 값이 유효한 
length 속성을 가지고 있는지 확인해야 합니다.

<Span fontSize="24px" fontWeight="bold" textAlign="right">
   {speakers[selectedChatRoomIndex].length}
</Span>
              
//수정

<Span fontSize="24px" fontWeight="bold" textAlign="right">
    {speakers[selectedChatRoomIndex]?.length || 0}
  </Span>

 

?. 연산자 (옵셔널 체이닝 연산자)

이 연산자는 객체 체인 내에서 중간 단계의 값이 null 또는 undefined인 경우 에러를 발생시키지 않고 안전하게 접근할 수 있도록 도와준다

 

예시)

 

const person = {
  name: "Alice",
  address: {
    city: "New York",
    street: "123 ABC Street"
  }
};

console.log(person.address?.city);  // "New York"
console.log(person.address?.zipcode);  // undefined
console.log(person.address.street.length);  // TypeError: Cannot read property 'length' of undefined
console.log(person.address?.street.length);  // undefined

 

위의 예시에서 person.address?.cityperson.address가 존재하고

person.address.city에 접근할 수 있으므로 "New York"을 반환합니다.

반면에 person.address?.zipcodeperson.address가 존재하지만

person.address.zipcode에 접근할 수 없으므로 undefined를 반환합니다.

마지막 두 예시에서는 person.addressnull 또는 undefined이므로 에러가 발생하는 대신 undefined를 반환합니다.