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
Zur Übersicht
Jan Sauer

Mehr vom Devsquad...

Jan Sauer

Lucas stellt seinen Cluster vor

Lucas Meurer

MARP - Markdown Presentations

Hallo, ich bin Jörg Herbst!

Ich bin der CEO von newcubator und freue mich über jede Nachricht!

* Pflichtfeld