개발Story

Nullish 병합( ??) 연산자는 왼쪽 피연산자가 nullor undefined일 때 오른쪽 피연산자를 반환하고 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자입니다.

 

우리가 흔히 사용하는 논리연산자는 OR을 의미하는 '||' 연산자일 텐데,

이 연산자를 많이 사용해봤다면 알겠지만 불편한 점이 왼쪽 피연산자가 boolean으로 강제로 변환되어 false인지를 체크하기 때문에 0이나 ''(빈 값)을 그대로 출력하고 싶어도 출력할 수 없는 아이러니한 상황이 발생한다.

([JavaScript] 비교 시  false로 간주되는 것들)

 

그럴 때 nullish를 사용하면 된다.

 

[사용법]

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

첫번째는 왼쪽 피연산자가 null일 경우 오른쪽 피 연산자를 반환하여 foo값이 default string의 값을 확인 할 수 있다.

 

[&&, || 연산자 비교]

let blank = ''; // An empty string (which is also a falsy value)

let notFalsyText = blank || 'Hello world';
console.log(notFalsyText); // Hello world

let preservingFalsy = blank ?? 'Hi neighborhood';
console.log(preservingFalsy); // '' (as blank is neither undefined nor null)

let height = 0;
console.log(height || 100); // 100
console.log(height ?? 100); // 0

0이나 ""를 할당하기 위해 nullish를 사용하면 된다.

 

||, && 사용시 괄호를 제공하여 명시적으로 우선 순위를 나타내어 사용하여야 한다.

null || undefined ?? "foo"; // raises a SyntaxError

(null || undefined) ?? "foo"; // returns "foo"

 

https://mine-it-record.tistory.com/630

 

[ES6+] nullish 병합 연산자 (??)

nullish 병합 연산자는 왼쪽 연산자가 null 또는 undefined일 때 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자이다. 개념은 대충 알겠고 예제를 통해 좀 더 자세

mine-it-record.tistory.com

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

 

profile

개발Story

@슬래기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!