0

Background: I program in other languages (primarily Python, C, C++ etc.), so I am well versed with OOP and the new keyword (especially, coming from a C++ background).

I am playing with a snippet of Javascript in a page, where I need to compare dates.

Version 1 (I think this is the way to go)

 $('input#foo-create-submit').on('click', function(e){
    let start_date = new Date($('#id_start_date').val());
    let end_date = new Date($('#id_end_date').val());
    let today = new Date();
    
    /* custom logic follows ... */

 });

Version 2 (This also seems to work - i.e. logical operation between date objects work ...)

 $('input#foo-create-submit').on('click', function(e){
    let start_date = Date($('#id_start_date').val());
    let end_date = Date($('#id_end_date').val());
    let today = Date();
    
    /* custom logic follows ... */

 });

Is the new keyword merely syntactic sugar? or is the JS VM doing some type conversion/coercion behind the scene (in which case I need to be aware of potential gotchas).

Which of the two is the canonical way to approach this kind of problem?

Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • 2
    See the [documentation](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date#constructor). What a JS (constructor) function does with the `new` keyword can indeed vary. – Sebastian Simon Aug 29 '21 at 10:43
  • Those two bits of code don't have remotely the same behavior. Did you actually observe the values of `start_date`, `end_date`, etc. in each case? In JS, functions created with the `function` keyword can also serve as constructors. That doesn't mean they will behave the same with and without `new`. – JLRishe Aug 29 '21 at 10:49
  • *"Which of the two is the canonical way"*: they don't return the same thing, so it depends on what you need. – trincot Aug 29 '21 at 10:49

0 Answers0