Today I Learned

A Hashrocket project

JavaScript "falsy" values are still values

Having good defaults doesn’t mean always having them in the function signature. I try to provide good defaults for my function args when possible. I like to provide them in the signature, too. However, I ran into a case where doing it in an object destructure would have caused a bug.

This function receives an object (fruit) and returns its price based on its selectedRate. It is expected that selectedRate can be '', null, or undefined, in addition to constants like "standardRate". In any case that the selected rate doesn’t exist, standardRate should be used:

function getFruitPrice({ selectedRate = 'standardRate', ...fruit }) {
  //...
}

The code above doesn’t satisfy this requirement. JavaScript considers empty strings and null to be values even though they are falsy. So, we can’t rely on setting the default this way. Instead a better implentation might look like this:

function getFruitPrice(fruit) {
  const rateToUse = fruit.selectedRate || 'standardRate'
  // ...
}
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.