DEV Community

Discussion on: 3 Ways to Set Default Value in JavaScript

Collapse
 
moopet profile image
Ben Sinclair

Given that your "ouchy" if/elses are only checking for truthiness, you'd miss out the a = a; part in the real world, though.

// ✅ If/Else is much better
if (a) {
  a = a;
  // do something else
} else {
  a = b;
}

becomes just this:

if (!a) {
  a = b;
}

and copes with specific tests like:

if (a === undefined) {
  a = b;
}

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.

Collapse
 
jakebman profile image
jakebman • Edited
// ✅ Ternary works # Ternary does not work.
a = (a === undefined) ? a : b;

The code in this segment is backwards - you're setting a to a only if it is undefined, and using b in all other cases.