Study/JavaScript(Clean code)

[JavaScript][clean-code] Nullish coalescing operator

갈푸라떼 2022. 5. 31. 01:19

* Nullish coalescing operator(Null 병합 연산자)

(비교적 최근문법 예전에 나온 레거시형 브라우저에서는 돌아가지 않을 수 있다.)

function createElement(type, height, width) {
  const element = document.createElement(type || 'div');

  element.style.height = String(height || 10) + 'px';
  element.style.width = String(width || 10) + 'px';

  return element;
}

- 만약 width와 height값을 0이라는 값을 주게 된다면?

const el = createElement('div', 0, 0);

el.style.height // '10px'
el.style.width // '10px'

- 왜 이런 결과가 나오게 될까???

  >  0은 Falsy에 해당될 수 있기 때문이다. 따라서 기본값인 10이 출력된다.

 

* Null 병합 연산자를 이용한 경우

function createElement(type, height, width) {
  const element = document.createElement(type ?? 'div');

  element.style.height = String(height ?? 10) + 'px';
  element.style.width = String(width ?? 10) + 'px';

  return element;
}

const el2 = createElement('div', 0, 0);

el2.style.height // '0px';
el2.style.width // '0px';
  • Falsy를 써야할까 null과 undefined에 대해서 평가해야할까에 대해서 판단을 해야한다.
  • Null 병합 연산자 : Null과 undefined에서만 사용해야한다.
  • Early return을 사용하여도 null 병합연산자와 or연산자에 대해서 분리를 생각하여야 한다.
    • 아래의 예시 코드 참조

* Early return을 사용

function helloWorld(message) {
  if (!message) {
    return 'Hello! World';
  }

  return 'Hello! ' + (message || 'World');
}

console.log(helloWorld(0)); // Hello! World

function helloWorld(message) {
  return 'Hello! ' + (message ?? 'World');
}

console.log(helloWorld(0)); // Hello! 0

 

* 실수를 방지하고자 문법 자체에서 제약

console.log(null || undefined ?? "foo")
  • Logical expressions and coalesce expresstion cannot be mixed 에러 발생
  • 실수를 방지하기 위해 문법 자체에서 제약 해버림

* 해결방법

console.log((null || undefined) ?? "foo")

 

- or는 연산자 우선순위에서 낮은 우선순위이다. 따라서 우선순위를 명시적으로 구분지어주어야한다.

 

 

(참조) default parameter를 사용하면 되는데 추후에 함수 파트에서 알아볼 예정