Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- react
- python
- PRISMA
- mongo
- frontend
- Express
- API
- ML
- Three
- CV
- Linux
- CSS
- figma
- PyTorch
- GAN
- DB
- SOLID
- nodejs
- postgresql
- ps
- C++
- Git
- backend
- js
- sqlite
- review
- vscode
- html
- ts
- UI
Archives
- Today
- Total
아카이브
[JS] Syntax | 15. Optional chaining - 속성 존재여부 확인하기 본문
JavaScript에서 객체에 대한 조건문을 작성할 때, 특정 속성값이 있는지의 여부가 중요하게 작용할 때가 있습니다.
const user1 = {
'name': 'Jhon',
'age': 20,
'membership': 'plus',
}
const user2 = {
'name': 'Mary',
'age': 20,
}
// user2는 membership을 속성값으로 가지지 않기 때문에 에러가 발생합니다
if (user1.membership === 'plus' && user2.membership === 'plus'){
console.log('all of them have plus membership');
}
이 경우, 해당 객체에 속성값이 존재하는지 먼저 확인한 수 조건문을 작성해야 합니다.
// membership의 존재 여부를 파악합니다.
if (user2.membership === undefined) {
console.log("there is no membership");
} else {
console.log(user2.membership);
}
// 속성값을 다룰 때는 조건 연산자를 이용한 처리도 가능합니다.
console.log(user2.membership && user2.membership.splice(2));
하지만 속성 이름이 길어지고 객체의 계층이 깊어질 수록 코드도 늘어나기 때문에, optional chaining(?) 구문을 통해 간단하게 나타내는 것이 좋습니다.
// ?가 붙은 속성값이 존재한다면 이후 접근을 처리하고, 그렇지 않으면 undefined를 반환합니다.
console.log(user2.membership?.splice(2));
728x90
'Language > JavaScript' 카테고리의 다른 글
[JS] Syntax | 17. 예외처리 (0) | 2025.04.06 |
---|---|
[JS] Syntax | 16. 구조분해(Destructuring) (0) | 2025.04.05 |
[JS] Syntax | 14. 계산된 속성명 (computed property name) (0) | 2025.04.04 |
[JS] Syntax | 13. Spread - 배열 또는 객체 분해하기 (0) | 2025.04.02 |
[JS] Syntax | 12. Arrow function (0) | 2025.03.31 |
Comments