What does the construct x = x || y mean?

opHASnoNAME picture opHASnoNAME · May 10, 2010 · Viewed 129.3k times · Source

I am debugging some JavaScript, and can't explain what this || does?

function (title, msg) {
  var title = title || 'Error';
  var msg   = msg || 'Error on Request';
}

Can someone give me an hint, why this guy is using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.

Answer

cletus picture cletus · May 10, 2010

It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".

It's shorthand for writing:

if (!title) {
  title = "Error";
}

This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:

a OR b

it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:

var title = title || "Error";

basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.