Javascript new Date vs new Date Object

Ravi Ram

Can someone help me uderstand what the following JavaScript code is doing? Specifically related to the new Date = new Date

// An array of dates
var eventDates = {};
eventDates[ new Date( '10/04/2017' )] = new Date( '10/04/2017' );
eventDates[ new Date( '10/06/2017' )] = new Date( '10/06/2017' );
eventDates[ new Date( '10/20/2017' )] = new Date( '10/20/2017' );
eventDates[ new Date( '10/26/2017' )] = new Date( '10/26/2017' );

It seems like this is the same?

// An array of dates
var eventDates = {};
eventDates[ new Date( '10/04/2017' )];
eventDates[ new Date( '10/06/2017' )];
eventDates[ new Date( '10/20/2017' )];
eventDates[ new Date( '10/26/2017' )];

Here is the console.log for each array.

enter image description here

Daniel Beck

The first example results in an object with keys based on the user's locale's string representation for dates, each containing the same value as a Date object. This is not particularly useful, in part because the keys will differ depending on the user's locale, and because in order to access the value of one of those keys, you would need to know the date that matches it... which is the value you'd be looking up in the first place.

The second example results in an empty object (because it just references each "key", without assigning a value to it.)

var eventDates = {};
eventDates[new Date('10/04/2017')] = new Date('10/04/2017');
eventDates[new Date('10/06/2017')] = new Date('10/06/2017');
eventDates[new Date('10/20/2017')] = new Date('10/20/2017');
eventDates[new Date('10/26/2017')] = new Date('10/26/2017');
console.log(eventDates);

var eventDates2 = {};
eventDates2[new Date('10/04/2017')];
eventDates2[new Date('10/06/2017')];
eventDates2[new Date('10/20/2017')];
eventDates2[new Date('10/26/2017')];

console.log(eventDates2)

It's not clear to me what the author of either of these examples was trying to accomplish. If you really wanted an array of dates, you would instead do this:

var eventDatesArray = [];
eventDatesArray.push(new Date('10/04/2017'));
eventDatesArray.push(new Date('10/06/2017'));
eventDatesArray.push(new Date('10/20/2017'));
eventDatesArray.push(new Date('10/26/2017'));

console.log(eventDatesArray);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related