지금까지 코드를 작성할 때 어떤 값이 null과 undefined인 경우 특정한 값을 할당하기 위해 || 연산자를 계속 사용해왔다. 그런데 || 연산자를 사용해서 null과 undefined를 확인하는 것은 잘못된 방식이라는 것을 알게 되었다.
|| 연산자는 null과 undefined만 확인하는 것이 아니라 falsy 값들을 모두 확인할 수 있는 연산자이다.
const a = '';
const b = a || '123';
console.log(b); // '123'
const c = 0;
const d = c || 123;
console.log(d); // 123
|| 연산자를 사용하면 null과 undefined만 처리하는 코드의 의도에서 벗어나게 되고 의도치 않은 에러가 발생할 수 있다.따라서 null과 undefined만 처리하려면 널 병합 연산자를 사용하는 것이 좋다.
널 병합 연산자(??)는 falsy 값들을 모두 구분하는 것이 아니라 falsy 값 중에서
null과undefined만 구분한다.
const a = '';
const b = a ?? '123';
console.log(b); // ''
const c = 0;
const d = c ?? 123;
console.log(d); // 0
const e = null;
const f = e ?? "fff";
console.log(f); // 'fff'
const g = undefined;
const h = g ?? 123;
console.log(h); // 123
null과 undefined만 구분해서 뒤에 있는 값을 할당하는 것을 알 수 있다.null과 undefined인 경우 특정 값을 할당하려면 || 연산자가 아니라 널 병합 연산자를 사용해야 한다.
널 병합 연산자와 함께 옵셔널 체이닝 연산자를 사용하면 좋다. 옵셔널 체이닝 연산자는 역할은 다음과 같다.
옵셔널 체이닝 연산자(?.)는
null이나undefined에 대해 프로퍼티에 접근하는 경우 발생하는 에러를 방지해준다.
const a = null;
console.log(a.b); // TypeError: Cannot read properties of null (reading 'b')
const c = undefined;
console.log(c.d); // TypeError: Cannot read properties of undefined (reading 'd')
null이나 undefined에 대해 프로퍼티에 접근하면 TypeError가 발생하는 것을 볼 수 있다.이런 경우 옵셔널 체이닝 연산자를 사용하면 에러가 발생하는 걸 방지할 수 있다.
const a = null;
console.log(a?.b); // undefined
const c = undefined;
console.log(c?.d); // undefined
const f = { g: 123 };
console.log(f?.g); // 123
null과 undefined에 대해 프로퍼티에 접근해도 TypeError가 발생하지 않고 undefined가 반환되는 것을 알 수 있다.널 병합 연산자와 옵셔널 체이닝 연산자는 궁합이 좋다. 옵셔널 체이닝 연산자가 반환하는 undefined를 널 병합 연산자를 사용해 처리할 수 있기 때문이다.
const a = null;
const b = a?.b ?? 123;
console.log(b); // 123
a 에 할당된 값이 null이기 때문에 a?.b는 undefined가 된다.undefined를 널 병합 연산자로 확인하고 뒤에 있는 123을 b에 할당한다.이렇게 옵셔널 체이닝 연산자와 널 병합 연산자를 함께 사용할 수 있다.