JavaScript – Ternary Operator vs. ||: Which to Use?

javascriptsyntax

I was taking a look at some node.js code earlier, and I noticed that the guy who wrote it seemed to favour the following syntax:

var fn = function (param) {
    var paramWithDefault = null == param ? 'Default Value' : param;
}

Over what I consider to be the more concise:

var fn = function (param) {
    var paramWithDefault = param || 'Default Value';
}

I was wondering if the second form is actually more socially acceptable JavaScript syntax, I've seen it out in the wild more times than the ternary operator for this purpose.

I note that in the first example he's using the double equals (not the triple equals) which means it will count "undefined" as null, which would reduce one impact that I could think of. However, I've read in numerous places that == is a rather evil operator in JavaScript (JSLint is very much against it, IIRC).

Best Answer

Because this code would evaluate to 'Default Value' everytime you passed in 0, "", false, or some other falsy value.

function fn(param) {
  var paramWithDefault = param || 'Default Value';
  return paramWithDefault;
}

It might not bite you on how you use this particular function, but it is a bad pattern to avoid when you do care about passing in things like empty strings or 0 or a boolean.

Related Topic