DEV Community

3 Ways to Set Default Value in JavaScript

Samantha Ming on March 18, 2019

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...
Collapse
 
mustafaabobakr profile image
Mostafa Abobakr

We can make a helper function

export function defaultValue(VAL, DEFAULT) {
  switch (VAL) {
    case 'null':
    case 'undefined':
    case null:
    case undefined:
      return DEFAULT;
    default:
      return VAL;
  }
}

const a = defaultValue( $(el).val() , 'ok');  // a = 'ok' .... if   $(el).val() === to any case  πŸ‘†
Collapse
 
fluffynuts profile image
Davyd McColl

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 || (:

Collapse
 
samanthaming profile image
Samantha Ming

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 😡

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.

Collapse
 
tombarr profile image
Thomas Barrasso

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.

const withZeroValue = (target, zeroValue = 0) => new Proxy(target, {
  get: (obj, prop) => (prop in obj) ? obj[prop] : zeroValue
})

let position = withZeroValue({
  x: 10,
  y: 15
})

position.z // 0