2.12 Nullish coalescing operator '??'

히진로그·2022년 2월 2일
0

Modern-Javascript

목록 보기
9/14

출처: https://javascript.info/

  • 혼자 읽고 타이핑하며 이해하면서 공부한 흔적 남기기

*A recent addition

As it treats null and undefined similarly, we'll use a special term here, in this article. We'll say that an expression is "defined" when it's neither null nor undefined.

null도 undefined도 아니면 defined이라고 표현하기로 한다.

The result of a ?? b is:

  • if a is defined, then a,
  • if a isn't defined, then b.

In other words, ?? returns the first argument if it's not null/undefined. Otherwise, the second one.

다시말해서 ?? 는 null/undefined이 아니라면 첫 번째 인수를 리턴한다. 그렇지 않으면 두번째 인수를 리턴한다.

let user;
alert(user ?? "Anonymous"); // Anonymous

첫 번째 인수인 user가 undefined이기 때문에 두번째 인수인 Anonymous가 리턴된다.

We can also use a sequence of ?? to select the first value from a list that isn't null/undefined.

Comparison with ||

The important difference between them is that:

  • || returns the first truthy value.
  • ?? returns the first defined value.

다시 말해서, ||false0, an empty string "" and null/undefined 의 차이를 구분할 수 없다. 그들은 모두 falsy value이다.

Precedence

The precedence of the ?? operator is the same as ||.

operator ?? is evaluated before = and ?, but after most other operations, such as +, *.

operator ?? 를 다른 오퍼레이터와 같이 쓸때, parantheses 괄호를 같이 쓰는 것을 고려해야 한다.

Using ?? with && or ||

괄호를 사용해서 확실히 구분해주지 않는 이상, ?? 와 &&, || 를 같이 쓰는 것을 금지한다.

0개의 댓글