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
  • 16,278
  • 7
  • 48
  • 74
Steven Harlow
  • 631
  • 2
  • 11
  • 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

3

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
  • 103,633
  • 15
  • 192
  • 229