JavaScript nullish coalescing

using optional shorthand ways to write if/else statements

// updated 2025-05-10 12:23

We can use nullish coalescing with ternary operators in JavaScript to reduce the number of lines of code when writing simple if/else statements:

1function calculatePrice(price, taxes, desc) {
2
3  // using nullish coalescing
4  
5  taxes = taxes ?? 0.05
6  desc = desc ?? "default item"
7  
8  const total = price * (1 + taxes)
9    console.log(`${desc} with tax: $${total}`)
10  
11}
12
13calculatePrice(100, 0.07, "Item A")
14calculatePrice(100, 0, "Item B")
15calculatePrice(100, undefined, undefined)
16
17/* output: 
18"Item A with tax: $107"
19"Item B with tax: $100" 
20"Default item with tax: $105"

Compare that with ternary operators but without nullish coalescing:

1function calculatePrice(price, taxes, desc) {
2
3  // using ternary operators
4  
5  taxes = (taxes >= 0) ? taxes : 0.05
6  desc = (desc || desc == "") ? desc : "Default item"
7  
8  const total = price * (1 + taxes)
9  console.log(`${desc} with tax: $${total}`)
10  
11}
12
13calculatePrice(100, 0.07, "Item A")
14calculatePrice(100, 0, "Item B")
15calculatePrice(100, undefined, undefined)
16
17/* output: 
18"Item A with tax: $107"
19"Item B with tax: $100" 
20"Default item with tax: $105"

Also, compare that with neither ternary operators nor nullish coalescing:

1function calculatePrice(price, taxes, desc) {
2
3  // using if statements
4  
5  if (taxes >= 0) {
6    taxes = taxes
7  } else {
8    taxes = 0.05
9  }
10  
11  if (desc || desc == "") {
12    desc = desc
13  } else {
14    desc = "default item"
15  }
16  
17  const total = price * (1 + taxes)
18  console.log(`${desc} with tax: $${total}`)
19  
20}
21
22calculatePrice(100, 0.07, "Item A")
23calculatePrice(100, 0, "Item B")
24calculatePrice(100, undefined, undefined)
25
26/* output: 
27"Item A with tax: $107"
28"Item B with tax: $100" 
29"Default item with tax: $105"
⬅️ older (in textbook-javascript)
📒 JavaScript ternary operators
newer (in textbook-javascript) ➡️
JavaScript read-only objects 📒
⬅️ older (in code)
📒 JavaScript ternary operators
newer (in code) ➡️
JavaScript read-only objects 📒
⬅️ older (posts)
📒 JavaScript ternary operators
newer (posts) ➡️
JavaScript read-only objects 📒