1

I ran across this in the bootstrap-datepicker.js file.

In the _setDate function the author does

this.viewDate = date && new Date(date)

They also do it a couple other times. What is this doing and why can't they just set

this.viewDate = date

or

this.viewDate = new Date(date)

https://github.com/eternicode/bootstrap-datepicker

Huangism
  • 15,899
  • 5
  • 47
  • 67
Steven Harlow
  • 556
  • 2
  • 10
  • 26
  • 2
    @karthikr: No, that's not [how logical operators work in JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators). – Felix Kling Oct 01 '14 at 20:45
  • Maybe this is a better duplicate: http://stackoverflow.com/a/12162443/218196. Or any of these: http://stackoverflow.com/search?q=%5Bjavascript%5D+%22%26%26%22 – Felix Kling Oct 01 '14 at 20:49

1 Answers1

2

If date value is falsy (in this case, null or undefined most probably; '' (empty string), 0 (a number), NaN and false itself also fit), it is assigned to this.viewDate - and new Date part won't even be evaluated. Otherwise new Date(date) is assigned to this.viewDate.

This is roughly equivalent to...

this.viewDate = date ? new Date(date) : date;

... or, even more verbose:

if (date) {
  this.viewDate = new Date(date);
}
else {
  this.viewDate = date;
}
raina77ow
  • 99,006
  • 14
  • 190
  • 222