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).

 1// Logical OR ||
 2console.log('' || 'default') // 'default'
 3console.log('test' || 'default') // 'test'
 4
 5console.log(0 || 'default') // 'default'
 6console.log(12 || 'default') // 12
 7
 8console.log(false || 'default') // 'default'
 9console.log(true || 'default') // true
10
11console.log(undefined || 'default') // 'default'
12console.log(null || 'default') // 'default'
13
14// Nullish coalescing ??
15console.log('' ?? 'default') // ''
16console.log('test' ?? 'default') // 'test'
17
18console.log(0 ?? 'default') // 0
19console.log(12 ?? 'default') // 12
20
21console.log(false ?? 'default') // false
22console.log(true ?? 'default') // true
23
24console.log(undefined ?? 'default') // 'default'
25console.log(null ?? 'default') // 'default'

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