javascriptor-operatortruthiness

What does the || (logical OR, double vertical line) operator do with non-boolean operands?


I am using a large JS library to perform certain drawing operations in canvas. Reviewing the library code (to make accommodating changes), I have ran into the || operator being used in a fashion which certainly should not evaluate to Boolean. Does this mean that this is a different operator or am I missing something obvious? An example follows:

var $time = Date.now || function() {
  return +new Date;
};

Solution

  • The || operator evaluates to the first operand if it can be converted to true or the last operand otherwise. So in your example $time will be Date.now if it exists or the declared function otherwise.