Emilio Emilio - 1 year ago 52
Javascript Question

typeof !== "undefined", comparing dates, new Date, Math.min / What is wrong with this simple js code?

I already spent 3 hours on that!
This code is on my nodeJS server. Everytime the server gets to it, it crashes. Don't know what's wrong... Could someone help me?

dateArray[11], dateArray[12] and dateArray[13] are either empty or are Date values

var dateArray11 = null;
var tempDateValue = "";
if ((typeof dateArray[11] !== "undefined") || (typeof dateArray[12] !== "undefined") || (typeof dateArray[13] !== "undefined")) {
dateArray11 = new Date(Math.min((dateArray[11].getTime()), (dateArray[12].getTime()), (dateArray[13].getTime())));
if (dateArray11.getTime() === dateArray[11].getTime()) {
tempDateValue = 11;
if (dateArray11.getTime() === dateArray[12].getTime()) {
tempDateValue = 12;
if (dateArray11.getTime() === dateArray[13].getTime()) {
tempDateValue = 13;

Answer Source

Since you said that dateArray[11], dateArray[12] and dateArray[13] are either empty or are Date values.

You cannot call a getTime() function of an empty or undefined value.

Before you call it, you should check if dateArray[11], dateArray[12] and dateArray[13] are Date Objects. You can see how to check that in this answer: http://stackoverflow.com/a/643827/3442014

EDIT: This is my aproach of what you're doing:

var dateArray=[];
dateArray[11]=new Date("2011/06/31");
dateArray[12]=new Date("2011/06/26");

var tempDateValue = "";

var dates=[];
if (dateArray[11] instanceof Date) dates.push(dateArray[11]);
if (dateArray[12] instanceof Date) dates.push(dateArray[12]);
if (dateArray[13] instanceof Date) dates.push(dateArray[13]);

var min = new Date(Math.min.apply(null,dates));

var tempDateValue = dates.map(Number).indexOf(+min) + 11;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download