Optional Chaining (?.)
참고) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Optional chaining (?.) - JavaScript | MDN
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error
developer.mozilla.org
let test = {}
console.log(test.a.b) // TypeError: Cannot read properties of undefined
console.log(test && test.a && test.a.b) // undefined (에러 발생하지 않음)
위와 같이 중첩 객체의 특정 프로퍼티에 접근하기 위해서는 &&를 사용해야만 함
이 경우 코드가 길어지는 단점이 있어 이러한 문제를 해결하기 위해 ?. 문법 탄생
?.
let test = {} // or null or undefined
console.log(test?.a) // undefined
console.log(test?.a.b) // undefined
?.[]
// []를 사용해 객체 프로퍼티에 접근
let user1 = {
name: "아무개",
age: 21,
address: {
country: 'Korea',
city: 'Seoul'
}
}
let user2 = null
let key1 = "name"
console.log(user1?.[key1]) // 아무개
console.log(user2?.[key1]) // undefined
let key2 = 'address'
console.log(user1?.[key2]?.country) // Korea
console.log(user1?.[key2]?.address?.city?.zipcode) // undefined
특정 프로퍼티 삭제
delete user?.name; // user가 존재하면 user.name을 삭제합니다.
※ 단, 옵셔널 체이닝은 존재하지 않아도 되는 대상에만 사용해야하며, 읽기 혹은 삭제는 가능하지만 쓰기에는 사용 불가!
user?.name = "홍길동"; // SyntaxError: Invalid left-hand side in assignment
// 에러가 발생하는 이유는 undefined = "홍길동"이 되기 때문
Nullish coalescing operator (??)
참고) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
developer.mozilla.org
let test = null; // null or undefined
let res = test ?? 'test가 null이거나 undefined면 이 값으로 대체할거야';
console.log(res) // test가 null이거나 undefined면 이 값으로 대체할거야
※ Vue2는 기본적으로 해당 문법을 지원하지 않기 때문에 바벨 플러그인 설치 필요
'개발 공부 > JavaScript + jQuery' 카테고리의 다른 글
[JavaScript] var, let, const 차이점 / 호이스팅 (0) | 2022.01.27 |
---|---|
[jQuery] Ajax, JSON 활용 & 동기와 비동기의 개념 (0) | 2021.09.01 |
[JavaScript/jQuery] toggleClass() (0) | 2021.08.17 |