javascript

JavaScript new Date() problems


Reading a previous question about the Date object in JavaScript I pointed out on my notebook the following problem:

var date1 = new Date('2015','02','31');

The command: alert(date1.getDay()); runs correctly!

What happens on my computer with IE and Chrome? If I debug I see:

__proto__ Invalid Date

Why? I also write the command as:

var date1 = new Date(2015, 2, 10);

But the problem continues to be there.


Solution

  • This is not a bug and is entirely expected.

    In JavaScript, inheritance is based on objects.

    For some reason - the engine designers thought it would be a great idea that the prototypical date - the one every single date object inherits from would be the invalid date. It's the same as Date.prototype. (Read about it here)

    All JavaScript objects have (In ES6, also non normative) a __proto__ method that represents what object they inherit from.

    What the developer tools is telling you is that your date object inherits from the prototypical date - which is an invalid date. Your date object is just fine.