re: 3 Ways to Set Default Value in JavaScript VIEW POST

FULL DISCUSSION
 

Just beware of when you have an original value which is falsey, for example, I recently had to get a numeric value from either the body of a request or the query string, using swagger. Swagger, since it was informed that the value would be numeric, had already populated the model with a numeric value.

So I had code (kinda) like this:

return getValueFromBody() || getValueFromQuery();

The problem was that the value in the swagger body object was zero, so it was falling over to attempt to get the value from the query, where it didn't exist, so the final result was undefined! This caused me a bit of a puzzlement, and I had to rather use:

var fromBody = getValueFromBody();
return fromBody === undefined
    ? getValueFromQuery()
    : fromBody;

So if you're using ||, just watch out for valid falsey values: if you can use empty string, zero or an actual false as a value, don't use || (:

 

Yes! “||” will capture ALL falsy values listed in the article. Definitely something to be really mindful of. Thanks for sharing your example and emphasizing that point! Very important and a very common gotcha that can cause extreme headaches 😵

code of conduct - report abuse