Home Writing

til / difference between nullish coalescing (??) and logical or (||)

Logical OR, ||, uses the right-side value when the left side is falsy (empty string, 0, false, undefined, null). Nullish coalescing, ??, only uses the right-side value when the left side is nullish (null or undefined).

// Logical OR ||
console.log('' || 'default') // 'default'
console.log('test' || 'default') // 'test'

console.log(0 || 'default') // 'default'
console.log(12 || 'default') // 12

console.log(false || 'default') // 'default'
console.log(true || 'default') // true

console.log(undefined || 'default') // 'default'
console.log(null || 'default') // 'default'

// Nullish coalescing ??
console.log('' ?? 'default') // ''
console.log('test' ?? 'default') // 'test'

console.log(0 ?? 'default') // 0
console.log(12 ?? 'default') // 12

console.log(false ?? 'default') // false
console.log(true ?? 'default') // true

console.log(undefined ?? 'default') // 'default'
console.log(null ?? 'default') // 'default'

  • Loading next post...
  • Loading previous post...