Code/JavaScript

[Javascript] || , ?? 연산자 비교

codens 2021. 2. 6. 03:17

    자바스크립트 연산자  || (OR) , ?? (Nullish coalescing operator, 널 병합 연산자) 다른점



<script>

obj = {
        v1: true,
        v2: 1,
        v3: false,
        v4: 0,
        v5: "",
        v6: null,
        v7: undefined,
    };

    for (let n of Object.getOwnPropertyNames(obj)) {
        let v = obj[n];
        console.log(n, v, `[${v || "||"}]`, `[${v ?? "??"}]`);
    }

</script>

 

//------------------

* 결과

v1 true [true] [true]
v2 1 [1] [1]

 

v3 false [||] [false]
v4 0 [||] [0]
v5  [||] []


v6 null [||] [??]
v7 undefined [||] [??]

 

//--------------------------

* false로 판정되어 2번째항이 결과값이 되는 경우

||  : false, 0, '', null, undefined

?? : null, undefined



 

//----------------------------

//참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators




 

반응형