1. 사용법

null이나 undefinded이면 내가 정한 값을 리턴한다.

 

// null일 때 리턴
let firstName = null;
let username = firstName ?? "Guest";
console.log(username); // "Guest"

// undefined일 때도 마찬가지
let username = undefined ?? "Guest";
console.log(username); // "Guest"

 

2. undefined나 null 값을 처리할 때 쓰기 좋다.

어떨 때는 props를 쓸 때가 있고, 어떨 때는 안쓸 때가 있다. 그 때 AND 연산자를 쓰면 매번 undefined일 때 return;으로 종료를 시키는 식으로 해야한다. 그렇지만 nullish를 쓰면 그럴 필요가 없다.

(1) undefined일 때

  console.log(example ?? "null이나 undefined면 이거 쓰셈");
  console.log(example || "false면 이거 쓰셈");
  let example;

??을 썼을 때는 스무스하게 처리된다.

근데 || 썼을 때는 undefined여도 truth로 취급돼서 example을 그대로 출력하고 있다.

---

(2) false일 때

  let example = false;

(2-1) 0일 때, ""일 때

두 경우에도 모두 false이다. 

이런 특징 때문에 0이 할당될 수 있는 변수를 사용해 기능을 개발할 땐 || 보다 ??가 적합합니다.
  let example = 0;

----

  let example = "";

 

 

참고:

https://sebhastian.com/javascript-double-question-mark/ 

https://ko.javascript.info/nullish-coalescing-operator

+ Recent posts