본문 바로가기

JavaScript

[JavaScript] ?? 문법

우리가 조건을 처리할 때 가장 먼저 생각하는 것이 if문과 switch문이다. 

const ifCase = true; 

if(ifCase) console.log("True");

const switchCase = true;

switch(switchCase) {
    case true:
        console.log("True");
        break;
    default:
        console.log("False");
}

여기서 좀 더 간단하게 사용하고 싶은 경우에는 삼항연산자를 사용한다. 

const case = true; 

console.log(case ? "True" : "False")

 

최근에 알게된 것이 하나 더 있는데, ?? 연산자이다. ( 정확한 명칭은 아직 모르는 .... )

const a = undefinded;

console.log(a ?? "False")  // "False"

const b = "True";

console.log(b ?? "False") // "True"

const c = undefinded;
const d = c ?? [];

삼항 연산자에서 true인 경우 자신을 바로 return 해주는 연산자이다. 

무조건 삼항 연산자를 대체하는 연산자는 아니고 c,d 처럼 필요에 따라 바로바로 처리할 수 있는 경우 

사용하면 코드가 좀 더 깔끔할 것 같다. 

반응형