My go-to has always been the ternary operator for assigning a value to a variable conditionally. But ever since I discovered that β||β can be use...
For further actions, you may consider blocking this person and/or reporting abuse
We can make a helper function
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:
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:So if you're using
||
, just watch out for valid falsey values: if you can use empty string, zero or an actualfalse
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 π΅
Given that your "ouchy"
if
/else
s are only checking for truthiness, you'd miss out thea = a;
part in the real world, though.becomes just this:
and copes with specific tests like:
and that doesn't seem long or awkward to me; it seems explicit and readable.
Personally, I like the Elvis style (though it looks more like Jonny Bravo to me...) or the null coalescing operator you have in other languages (like SQL and nowadays even PHP), which has the benefit of being chainable like the
||
method.The code in this segment is backwards - you're setting
a
toa
only if it isundefined
, and using b in all other cases.Nice article, I would love to see the Elvis operator in Javascript!
Another way you can assign default values is with Proxy. This can be done explicitly, implicitly, on a per-type basis, etc.