Skip to content
Advertisement

What would be the purpose of if (thisValue.getTime() === thisValue.getTime())

I have inherited a web project in PHP and of course JS. What purpose would this code below serve in JavaScript? Seems that the ‘if’ would always be true and the else will never execute. The developer who wrote this is no longer accessible to be asked what he intended by this.

var thisValue = new Date($(this).val());
if (thisValue.getTime() === thisValue.getTime()){
  //some code
}else{
  //some code
}

Advertisement

Answer

getTime() should always be equal to itself if the new Date(unknown) is an actual date.

This looks like a hack for the scenario where val in new Date(val) is not a date, in this scenario getTime() should return NaN which is not equal to itself as it doesn’t exist.

Compiled output:

if (thisValue.getTime() (number or NaN) === (number or NaN)) {

} else (NaN is not equal to NaN) {

}

Instead of making a weird looking hack, this is cleaner and more readable:

if (!Number.isNaN(thisValue.getTime()) {} else {}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement