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';
}
Why is this guy using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.
It means the
titleargument is optional. So if you call the method with no arguments it will use a default value of"Error".It’s shorthand for writing:
This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:
it evaluates to
trueif eitheraorbistrue. So ifais true you don’t need to checkbat all. This is called short-circuit boolean evaluation so:basically checks if
titleevaluates tofalse. If it does, it “returns”"Error", otherwise it returnstitle.