3.4 JavaScript Nullish 병합, 삼항 연산자

지구·2023년 7월 18일
0

JavaScript

목록 보기
9/30

1. Nullish 병합(Nullish Coalescing)

a ?? b

OR 연산자를 사용한 경우

const n = 0

const num1 = n || 7
console.log(num1) // 7

이런 상황에서 숫자 0을 거짓의 의미가 아닌 유효한 숫자 데이터로 사용하고 싶은 경우가 있다.

Nullish 병합 연산자를 사용한 경우

const n = 0

const num1 = n ?? 7
console.log(num1) // 0

Nullish 병합 연산자는 null, undefined를 제외한 나머지 모든 데이터를 만나면 반환하게 된다.

console.log(null ?? 1) // 1
console.log(undefined ?? 2) // 2
console.log(null ?? undefined) // undefined
console.log(null ?? 1 ?? 2) // 1
console.log(false ?? 1 ?? 2) // false
console.log(0 ?? 1 ?? 2) // 0

2. 삼항(Ternary)

if (a < 2) {
	console.log ('참!')
} else {
	console. log('거짓...')
}
// 참!

삼항 연산자

// 조건 ? 참 : 거짓
console.log(a < 2 ? '참!' : '거짓') // 참!

코드를 간소화할 수 있어서 많이 사용된다.

profile
프론트엔트 개발자입니다 🧑‍💻

2개의 댓글

comment-user-thumbnail
2023년 7월 18일

잘 읽었습니다. 좋은 정보 감사드립니다.

답글 달기
comment-user-thumbnail
2023년 7월 18일

항상 좋은 글 감사합니다.

답글 달기