?? vs ||
들어가기 전
ES6 문법을 미리 숙지하지 않으면, 코드가 어떻게 동작하는지 짐작하기가 힘들다. 오늘은 ??
과 ||
문법에 대해 알아보자
개념
변수안에 있는 값이 null 이나 undefined 일 경우 default value를 세팅한다.
falsy value1인 0과 "" (empty string)일 경우에는 작동하진 않는다.
falsy value일 경우에도 default value로 넣고 싶을 때는 ||
syntax를 사용하면 된다.
Example
??
문법을 사용해보자
const a = undefined
const b = a ?? 'apple'
console.log(b) // apple
const a = null
const b = a ?? 'apple'
console.log(b) // apple
const a = ''
const b = a ?? 'apple'
console.log(b) // ''
const a = 0
const b = a ?? 'apple'
console.log(b) // 0
||
문법을 사용해보자
const a = ''
const b = a || 'apple'
console.log(b) // apple
const a = 0
const b = a || 'apple'
console.log(b) // apple