[JS] nullish-coalesing(null undefined 처리)

Brian·2021년 8월 25일
0

JavaScript

목록 보기
4/6
post-thumbnail

nullish-coalesing?

null 과 undefined를 간단하게 ES6 문법 "??" 으로 해결 하는 것이다.

function print(text){
   const text = 'text';
   
   if(text === null || text === undefined){
      console.log('nothing to print'); 
   }
  
  console.log(text);
}

  • 위 코드는 if 문을 통해서 text의 값이 null or undefined 가 아닌지 확인 하는 과정이다. 위 코드를 "??" 문법을 통해 아래 코드와 같이 간결하게 작성 할 수 있다.
function print(text){
   const msg = text ?? 'nothing to print';
   console.log(msg); 
}

print('hello'); //hello
print(null); // nothing to print
print(undefined); // nothing to print

  • 위 코드에서 인자값을 default로 지정하면 비슷한 결과가 있지 않을까??
function print(text = 'nothing to print'){
   console.log(text);
}

print('hello'); //hello
print(null); // null
print(undefined); // nothing to print

result:

  • default로 인자 값을 설정 했을 경우에는 null 처리를 하지 못 하는 것을 확인 할 수 잇다. undefined는 잘 처리 된다.
  • null 과 undefined 두개를 다 체크 하기 위해서는 nullish-coalesing 방식을 사용하는 것이 좋다.
  • undefined 일 때만 적용 된다.

nullish-coalesing vs logical OR operator

nullish - leftExpr ?? rightExpr ( leftExpr 이 null 혹은 undefined 일 경우에 rightExpr 실행)
OR - leftExpr || rightExpr ( leftExprt 이 false 일 경우에 rightExpr을 실행 시킨다.) false 에 해당 하는 경우 (false, null, undefined, NaN, 0. -0. "", '', `` )

nullish 와 or 은 명확하게 차이가 있기 때문에 이해를 하고 써야 한다.

Example #1

function run(text){
  const msg = text || 'nothing to display';
  console.log(msg);
}

run('hello'); // 'hello'
run(undefined); // nothing to display
run(null); // nothing to display
run(0); // nothing to display
run(''); // nothing to display
run(""); // nothing to display

Example #2

const result = getInitialState() ?? fetchFromServer();
console.log(result);

function getInitialState(){
  return null; 
}

function fetchFromServer(){
  return 'Hello yall';
}

//결과 : 'Hello yall"; 

reference : 드림코딩👍

profile
Jiujitsu_coder

0개의 댓글