단축 평가

shelly·2022년 5월 9일

논리 연산자 단축 평가 예시

true && 'hello' // 'hello'
false && 'hello' // false

true || 'hello' // true
false || 'hello' // 'hello'

optional chaining 연산자 예시

const elem = null
const value = elem?.length
console.log(value) // undefined

nullish coalescing 예시

?? 연산자를 기준으로 좌항이 null 혹은 undeifned 일 경우 우항을 반환하고, 그렇지 않으면 좌항을 반환한다.

const name = null ?? 'shelly'
console.log(name) // shelly

?? vs ||

true ?? 'shelly' // true
true || 'shelly' // true

false ?? 'shelly' // false
false || 'shelly' // 'shelly'

1 ?? 'shelly' // 1
1 || 'shelly' // 1

0 ?? 'shelly' // 0
0 || 'shelly' // 'shelly'

null ?? 'shelly' // 'shelly'
null || 'shelly' // 'shelly'

undefined ?? 'shelly' // 'shelly'
undefined || 'shelly' // 'shelly'

'' ?? 'shelly' // ''
'' || 'shelly' // 'shelly'

NaN ?? 'shelly' // NaN
NaN || 'shelly' // 'shelly'

[] ?? 'shelly' // []
[] || 'shelly' // 'shelly'

({}) ?? 'shelly' // {}
({}) || 'shelly' // {}
  • ??
    • 좌항이 null 혹은 undefined일 경우에만 우항의 값을 반환한다.
    • 따라서 default 값을 지정할 때 유용하다.
  • ||
    • 좌항을 Flase로 평가되는 Falsy값일 경우, 좌항이 False일 경우 우항의 값을 반환한다.

활용 예시

  • optional chaining 과 nullish coalescing 을 활용하여 default값 지정
const  obj = {dog : 'happy'}
const dogName = obj?.dog ?? 'cookie' // 'happy'
const catName = obj?.cat ?? 'nabi' //
  • &&연산자를 활용하여 if문 축약
const { status } = await api() // { status : 200}

if (status === 200) {
	console.log('success')
}
const { status } = await api() // { status : 200}
status === 200 && console.log('success')

0개의 댓글