신문법) ?. / ?? 연산자 (optional chaining)
자바스크립트에서 여러 문자, 숫자를 한 변수에 저장하고 싶다면, Object.
var user = {
name: 'kim',
age: 20
};
꺼내 쓰려면,
user.name; // 'kim'
use.age; // 20;
?. (optional chaning 연산자)
- 왼쪽에 있는 자료가 비어있으면, 오른쪽을 실행해주지 않는다.
- 즉, ?. 왼쪽이 null, undefined면 점안찍어주고 undefined 남겨준다.
언제쓰나?
중첩된 object 자료에서 자료뽑을 때 reference 에러 없이 안전하게 뽑을 수 있음
예로 들어보자. 중첩된 object를 만들어보자.
var user = {
name: 'kim',
age: {value: 20}
};
console.log(user.age.value); // 20
근데 만약 실수로 age 항목을 만들지 않았다고 하자.
var user = {
name: 'kim',
// age: {value: 20}
};
console.log(user.age.value); // 에러발생: Cannot read properties of undefined
에러가 발생해서 에러가 발생한 곳에서 코드 실행이 중단된다. 근데 실행이 중단되면 안되잖아!
이런 경우를 대비해서 에러를 미리 예방하는 코드를 작성하면 좋다. 그럴 때 optional chaining을 사용하면 좋다.
console.log(user.age?.value); // undefined
user.age가 undefined니까 undefined를 반환한다.
남용하지 말기
var user = {
name: 'kim'
};
conosle.log(user?.age);
이런 경우에는 user 옆에 ?.를 써줄 필요가 없다. 왜냐하면 user는 무조건 존재하고 있는 상태니까.
conosle.log(user.age); // undefined
자바스크립트는 object에서 점을 찍었는데 항목이 없으면 자동으로 undefined를 붙여준다.
console.log(user.age.value); // TypeError: cannot read properties of undefined
근데 undefined에서 점을 두 개 찍을 때가 문제가 된다.
undefined.value (에러남)
null.value (에러남)
HTML 조작할 때 사용
document.querySelector('#a').innerHTML
이거 잘 보면 점이 두개 있다. 이것도 실은 중첩된 object다. 그래서 이렇게 코드를 짰는데 #a인 element가 없으면 undefined.innerHTML이 되니까 에러가 발생한다.
에러가 나고 싶지 않으면 optional chaining을 작성하자.
document.querySelector('#a')?.innerHTML
주의할 점
물음표 문법은 에러를 해결해주는 게 아니라 에러를 잠시 감추는 문법이기 때문에 꼭 필요한 곳에서만 사용해야 한다.
?? (nullish coalescing 연산자)
- 왼쪽이 undefined, null이면 오른쪽의 것을 대신 반환한다.
conosle.log(undefined ?? '으잉');
사용하는 곳
user에 데이터가 있고, 이 데이터를 보여준다고 하자.
var user;
console.log(user);
근데 만약 데이터가 늦게 3초 후에 도착한다면? 그러면 undefined가 화면에 출력될거다. 그럴 때 ??를 사용한다.
console.log(user ?? '로딩중');
더 안전하게 변수를 보여줄 수 있다.
?? vs ||
그럼 이때 드는 의문이 있다. ??랑 ||랑 차이점이 뭔가?
|| (OR operator)
- 왼쪽이 falsey일 때 오른쪽을 반환한다.
- 자바스크립트에서 아래 것들을 falsy로 간주한다.
- **0**
- **-0**
- **0n**
- **NaN**
- **"" (빈 문자열)**
- **false**
- **null**
- **undefined**
console.log(12 || "not found") // 12
console.log(0 || "not found") // "not found"
console.log("jane" || "not found") // "jane"
console.log("" || "not found") // "not found"
console.log(true || "not found") // true
console.log(false || "not found") // "not found"
console.log(undefined || "not found") // "not found"
console.log(null || "not found") // "not found"
?? (nullish coalescing)
- 왼쪽이 **null, undefined** 일 때 오른쪽을 반환한다.
console.log(12 ?? "not found") // 12
console.log(0 ?? "not found") // 0
console.log("jane" ?? "not found") // "jane"
console.log("" ?? "not found") // ""
console.log(true ?? "not found") // true
console.log(false ?? "not found") // false
console.log(undefined ?? "not found") // "not found"
console.log(null ?? "not found") // "not found"
즉, ??는 ||에 포함된다(?)고 볼 수 있겠다.

'Front-End: Web > JavaScript' 카테고리의 다른 글
[js] includes vs in (0) | 2022.11.16 |
---|---|
[js] Math.floor vs trunc vs parseInt (0) | 2022.11.16 |
[코딩애플] js part 3-12. class로 만들어보는 2D 게임 (0) | 2022.10.22 |
[코딩애플] js part 3-11. shadow DOM과 template으로 HTML 모듈화하기 (0) | 2022.10.22 |
[코딩애플] js part 3-10. Web Components: 커스텀 HTML 태그 만들기 (0) | 2022.10.22 |