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:

function calculatePrice(price, taxes, desc) {

  // using nullish coalescing
  
  taxes = taxes ?? 0.05
  desc = desc ?? "default item"
  
  const total = price * (1 + taxes)
    console.log(`${desc} with tax: $${total}`)
  
}

calculatePrice(100, 0.07, "Item A")
calculatePrice(100, 0, "Item B")
calculatePrice(100, undefined, undefined)

/* output: 
"Item A with tax: $107"
"Item B with tax: $100" 
"Default item with tax: $105"

Compare that with ternary operators but without nullish coalescing:

function calculatePrice(price, taxes, desc) {

  // using ternary operators
  
  taxes = (taxes >= 0) ? taxes : 0.05
  desc = (desc || desc == "") ? desc : "Default item"
  
  const total = price * (1 + taxes)
  console.log(`${desc} with tax: $${total}`)
  
}

calculatePrice(100, 0.07, "Item A")
calculatePrice(100, 0, "Item B")
calculatePrice(100, undefined, undefined)

/* output: 
"Item A with tax: $107"
"Item B with tax: $100" 
"Default item with tax: $105"

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

function calculatePrice(price, taxes, desc) {

  // using if statements
  
  if (taxes >= 0) {
    taxes = taxes
  } else {
    taxes = 0.05
  }
  
  if (desc || desc == "") {
    desc = desc
  } else {
    desc = "default item"
  }
  
  const total = price * (1 + taxes)
  console.log(`${desc} with tax: $${total}`)
  
}

calculatePrice(100, 0.07, "Item A")
calculatePrice(100, 0, "Item B")
calculatePrice(100, undefined, undefined)

/* output: 
"Item A with tax: $107"
"Item B with tax: $100" 
"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 📒