JS

[JS] Nullish coalescing operator (??) + OR 연산자

emayom 2021. 12. 15. 21:34

비록 IE는 지원하지 않는다지만 nullish operator에 대해 간단하게 알아보자.

그리고 null, undefined 이외에도 '', 0, -0 등등 falsy를 모두 처리할 수 있는 ?? OR 연산자도 조금 더 알아보자.


Nullish coalescing operator (??)

 

오늘의 기록은 nullish 연산자 !!

nullish 연산자는 데이터 값이 null 이거나 undefined일 경우의 처리를 간단하게 표현할 수 있다!

 

예를 들어,

아래와 같이 작성하게 된다면,,,

보기에도 복잡해보이고 딱히 효율적이라고는 할 수 없는 코드가 완성된다 ~!

 

const findFalsy = (data) => {
    var result;
    if(data == null || data == undefined){
    	result = 'me ? falsy ... ';
    }
    console.log(result);
    return result;
}

 

만약 nullish 연산자로 수정하게 된다면?

아래와 같이 같은 코드를 읽기 쉽게 작성할 수도 있다 ㅎㅎㅎㅎ

 

const findFalsy = (data) => {
    console.log(data);
    return data ?? 'me ? falsy ... ';
}

 

하지만 ..! 꼭 null 이거나 undefined가 아닌

falsy 모두를 처리하고 싶을 경우에는 OR 연산자로 간단하게 작성할 수 있다..!

항상 조건을 확인하는 부분에서만 사용하는건 줄 알았는데 ,,

아래와 같이 사용할 수 있다 !!

 

const falsy = {
    empty_string : '',
    number : 0,
    undefined : undefined,
    null : null,
}

const isThisFalsy = (data) => {
    for(let i in data){
        data[i] || console.log('logical :: ', data[i]);
        data[i] ?? console.log('nullish :: ', data[i]);
    }
}

 

결과를 확인해보면,

OR 연산자는 4개 모두를 false 로 판단한 반면,

nullish 연산자는 null 과 undefined만을 false로 판단했다!!

 


⚠️ 아래 내용은 모두 개인적인 참고 / 기록을 위한 용도입니다. 참고해주시고 편안하게 봐주세요 :)  ⚠️
***    혹시라도 잘못된 정보가 있다면  언제든지 알려주시면 감사하겠습니다  !    ***

 

 

Nullish coalescing operator (??) - JavaScript | MDN

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

developer.mozilla.org