Nullish 병합 연산자

Nullish 병합 연산자 (Nullish coalescing operator, ??)

왼쪽 피연산자가 null 또는 undefined일 때 오른쪽 피연산자를 반환하고, 그 외에는 왼쪽 피연산자를 반환하는 논리 연산자입니다. Baseline Widely available — 2020년 7월부터 여러 브라우저에서 지원되는 잘 정착된 기능입니다.

출처: Nullish coalescing operator (??)

본문

nullish 병합(??) 연산자는 왼쪽 피연산자가 null이나 undefined이면 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자입니다.

시도해 보기 (Try it)

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

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

구문 (Syntax)

leftExpr ?? rightExpr

설명 (Description)

nullish 병합 연산자는 논리 OR(||) 연산자의 특수한 경우로 볼 수 있습니다. OR 연산자는 왼쪽 피연산자가 null이나 undefined뿐만 아니라 어떤 falsy 값이어도 오른쪽 피연산자를 반환합니다. 다시 말해, ||를 사용해 다른 변수 foo에 어떤 기본값을 제공한다면, ''0 같은 일부 falsy 값을 쓸 수 있는 값으로 간주할 때 예상치 못한 동작이 발생할 수 있습니다.

nullish 병합 연산자는 연산자 우선순위가 다섯 번째로 낮습니다. ||보다 바로 낮고 조건(삼항) 연산자보다 바로 높습니다.

AND(&&) 또는 OR(||) 연산자를 ??와 직접 결합하는 것은 불가능합니다. 그런 경우 구문 오류가 발생합니다.

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

대신 괄호를 제공해 우선순위를 명시적으로 나타내세요:

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

예제 (Examples)

nullish 병합 연산자 사용하기

이 예제에서는 기본값을 제공하되 null이나 undefined가 아닌 값은 유지합니다.

const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;

const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;

console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42

변수에 기본값 할당하기

이전에는 변수에 기본값을 할당하고 싶을 때 논리 OR 연산자(||)를 쓰는 것이 일반적인 패턴이었습니다:

let foo;

// foo is never assigned any value so it is still undefined
const someDummyText = foo || "Hello!";

하지만 ||는 불리언 논리 연산자이므로 왼쪽 피연산자가 평가를 위해 불리언으로 강제 변환되고, 어떤 falsy 값(0, '', NaN, false 등)도 반환되지 않습니다. 0, '', NaN을 유효한 값으로 간주한다면 이 동작은 예상치 못한 결과를 초래할 수 있습니다.

const count = 0;
const text = "";

const qty = count || 42;      // 42  (0이 아님)
const message = text || "hi!"; // "hi!" (""이 아님)
console.log(qty); // 42
console.log(message); // "hi!"

nullish 병합 연산자는 첫 번째 연산자가 null 또는 undefined(다른 falsy 값은 아님)로 평가될 때만 두 번째 피연산자를 반환함으로써 이 함정을 피합니다:

const myText = ""; // 빈 문자열 (역시 falsy 값)

const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world

const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // '' (myText가 undefined도 null도 아니므로)

단락 (Short-circuiting)

OR 및 AND 논리 연산자처럼, 왼쪽이 nullundefined도 아님이 밝혀지면 오른쪽 표현식은 평가되지 않습니다.

function a() {
  console.log("a was called");
  return undefined;
}
function b() {
  console.log("b was called");
  return false;
}
function c() {
  console.log("c was called");
  return "foo";
}

console.log(a() ?? c());
// Logs "a was called" then "c was called" and then "foo"
// as a() returned undefined so both expressions are evaluated

console.log(b() ?? c());
// Logs "b was called" then "false"
// as b() returned false (and not null or undefined), the right
// hand side expression was not evaluated

옵셔널 체이닝 연산자(?.)와의 관계

nullish 병합 연산자는 undefinednull을 특정 값으로 취급합니다. null이나 undefined일 수 있는 객체의 속성에 접근하는 데 유용한 옵셔널 체이닝 연산자(?.)도 마찬가지입니다. 이 둘을 결합하면 nullish일 수 있는 객체의 속성에 안전하게 접근하고, 그럴 경우 기본값을 제공할 수 있습니다:

const foo = { someFooProp: "hi" };

console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"

명세 (Specifications)

nullish 병합 연산자는 ECMAScript 언어 명세에 정의되어 있습니다.

브라우저 호환성 (Browser compatibility)

이 기능은 대부분의 현대 브라우저에서 널리 지원됩니다(Baseline Widely available). 자세한 호환성 표는 MDN의 브라우저 호환성 섹션을 참고하세요.

더 알아보기