programming/Javascript
Javascript ?? (null 병합 연산자) 와 || (OR 연산자) 의 차이
euuuuuz:
2024. 8. 2. 11:28
|| : OR 연산자 (MDN)
Logical OR
논리 OR 계산용
둘 중 하나이상 참이면 👉 참
- true || false ⇒ true
- true || true ⇒ true
- false || false ⇒ false
?? : null 병합 연산자 (MDN)
왼쪽이 null 또는 undefined 이면 오른쪽을 반환, 아니면 왼쪽값 사용
UseCase
form 의 default 값을 지정하려한다
store 에 저장해둔 값이 있다면 사용하고,
없다면 기본값을 수동으로 지정하려 한다.
[Incorrect]
defaultValues: {
setBillingAddressAsShippingAddress: paymentForm?.setBillingAddressAsShippingAddress || true,
isManual: paymentForm?.isManual || false,
useOfTerms: paymentForm?.useOfTerms || false,
marketing: paymentForm?.marketing || false,
},
위 처럼 작성한 경우 OR 논리 연산을 하게 된다.
paymentForm.setBillingAddressAsShippingAddress 값이 false 인데, 뒤의 true 논리 연산에 의해 -> true 로 덮여짐
[Correct]
defaultValues: {
setBillingAddressAsShippingAddress: paymentForm?.setBillingAddressAsShippingAddress ?? true,
isManual: paymentForm?.isManual ?? false,
useOfTerms: paymentForm?.useOfTerms ?? false,
marketing: paymentForm?.marketing ?? false,
},
store 에 저장해둔 값이 있다면 사용하고(왼쪽값 리턴),
없다면 기본값을 수동으로 지정하려 한다(오른쪽 값 리턴).