null 과 undefined를 간단하게 ES6 문법 "??" 으로 해결 하는 것이다.
function print(text){
const text = 'text';
if(text === null || text === undefined){
console.log('nothing to print');
}
console.log(text);
}
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
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 - leftExpr ?? rightExpr ( leftExpr 이 null 혹은 undefined 일 경우에 rightExpr 실행)
OR - leftExpr || rightExpr ( leftExprt 이 false 일 경우에 rightExpr을 실행 시킨다.) false 에 해당 하는 경우 (false, null, undefined, NaN, 0. -0. "", '', `` )
nullish 와 or 은 명확하게 차이가 있기 때문에 이해를 하고 써야 한다.
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
const result = getInitialState() ?? fetchFromServer();
console.log(result);
function getInitialState(){
return null;
}
function fetchFromServer(){
return 'Hello yall';
}
//결과 : 'Hello yall";