Best approach Shortahand or Short-circuiting in Javascript

Viewed 66

Which approach is most recommended. First or Second ?

function(x,y) {
  // 1
  var foo = x ? x.a : y;
  // 2
  var foo = x && x.a || y;
} 
4 Answers

The first one

x ? x.a : y

returns with a truthy x a falsy value of x.a, where

x && x.a || y

returns y in this case.

To answer your question, it depends, if you have falsy values or not.

For a safe usage, depending only on x, you might use better the conditional operator.

First one - ternary operations are mostly used in these cases and developers don't have to remember boolean operators precedence.

In almost any other situation I prefer a ternary, but in the specific case of deep nesting I'd prefer short-circuiting. With deeper nesting it becomes:

var foo = (alpha && alpha.beta && alpha.beta.charely) ? alpha.beta.charley.delta : y

vs

var foo = (alpha && alpha.beta && alpha.beta.charely && alpha.beta.charley.delta) || y

It just feels like the former is already basically doing the latter, but then switching tactics on the last check. Just my opinion.

Personally, neither.

I use a get() helper method that some other languages have build in, if all I'm trying to do in get some deep value (without throwing an error if I don't have the parent object). It also allows for specifying a fallback value if the value is undefined, rather than falsy. e.g.:

var foo = get(x, 'a', 'Not found') || 'Denied'

Here, if x.a doesn't exist, I get, 'Not found', and if it does exists, but is falsy, I get 'Denied'.


There's also an "Optional Chaining" proposal for JavaScript (currently stage-1).

With it, the syntax would be:

var foo = x?.a || y;

or if you want to fallback to y only if it's specifically undefined (or null):

var foo = x?a ?? y;

using the "Nullish Coalescing" proposal (also stage-1).

Related