JavaScript ternary operators

using optional shorthand ways to write if/else statements
// updated 2025-05-11 11:41

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

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"

Compare that with the following more lengthy way:

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 string interpolation
newer (in textbook-javascript) ➡️
JavaScript nullish coalescing 📒
⬅️ older (in code)
📒 JavaScript string interpolation
newer (in code) ➡️
JavaScript nullish coalescing 📒
⬅️ older (posts)
📒 JavaScript string interpolation
newer (posts) ➡️
JavaScript nullish coalescing 📒