21.4.2021

Default Values in JavaScript?

The following function calculates a total price of an item. This should include taxes and also use defaults if some of the inputs are missing. What is the problem?

function calculatePrice(price, tax, description) {
  tax = tax || 0.05
  description = description || "Default item"
  const total = price * (1 + tax)
  console.log(`${description} for $${total}`)
}

calculatePrice(100, 0.07, "Shirt")
calculatePrice(100, 0, "Sneakers")
calculatePrice(100, undefined, "")
Result
Shirt for $107
Sneakers for $105
Default item for $105

But as the 0 tax for Sneakers is interpreted as false we get an incorrect price. Solution is to use the Nullish Coalescing Operator

function calculatePrice(price, tax, description) {
  tax = tax ?? 0.05
  description = description ?? "Default item"
  const total = price * (1 + tax)
  console.log(`${description} for $${total}`)
}

calculatePrice(100, 0.07, "Shirt")
calculatePrice(100, 0, "Sneakers")
calculatePrice(100, undefined, "")
Shirt for $107
Sneakers for $100
 for $105
Jan

Softwareentwickler

Zur Übersicht

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund