아카이브

[JS] Syntax | 10. 병합연산자(??) 본문

Language/JavaScript

[JS] Syntax | 10. 병합연산자(??)

Rayi 2025. 3. 23. 22:05

JavaScript에서는 and(&&)or(||) 연산을 할 때 첫 번째 값에 무엇이 오느냐에 따라 출력값이 달라집니다.

operand 1 operand 2 AND OR
Truthy Truthy  operand 2 operand 1
Truthy Falsy operand 2 operand 1
Falsy Truthy operand 1 operand 2
Falsy Falsy operand 1 operand 2

그리고 이를 이용하여 특정 변수에 기본값을 지정하는 코드를 작성할 수도 있습니다.

const perhapsNull = null;

// perhapsNull이 false라면 'notNull'을, true라면 perhapsNull을 반환합니다.
const value = perhapsNull || 'notNull';

여기서 true / false 값이 아니라 null & undefined 여부만 확인하고 싶다면, 병합 연산자 ?? 를 사용하면 됩니다.

const value1 = null ?? 'javascript'; // 'javascript'
const value2 = [] ?? ['1']; // []

??의 경우 null & undefined만 판단하기 때문에, 첫 번째 피연산자가 falsy여도 null 이나 undefined가 아니라면 그대로 반환된다는 차이가 있습니다.

728x90

'Language > JavaScript' 카테고리의 다른 글

[JS] Syntax | 12. Arrow function  (0) 2025.03.31
[JS] Syntax | 11. rest parameter - 가변 변수 사용하기  (0) 2025.03.29
[JS] ES에 대해서  (0) 2025.03.21
[JS] Library | 02. Papaparse  (1) 2024.12.10
[JS] Library | 01. Superstruct  (0) 2024.08.25
Comments