Thomas Thomas - 1 year ago 90
AngularJS Question

Comparing date to NaN and undefined

I have a pretty simple if statement but I don't use javascript too much so I think I have made an error somewhere. If you go to my page you can see the value gets alerted as undefined, but a block of code still gets skipped even though the if parameters are

== undefined
. Does it matter that this is an AngularJS app?

web page:


$scope.setDate = function (dateSelected) {
var now = new Date();
$scope.latest = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes());
$scope.hoursAgo = Math.round((($scope.latest - dateSelected) / 3600000) * 100) / 100;
if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN) {
alert("Please choose a date/time");
else {
alert('You lost your pet ' + $scope.hoursAgo + ' hour(s) ago');
$scope.checkDateSet = true;

Answer Source

To check if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN)

write like this

if ($scope.hoursAgo === 'undefined' || isNaN($scope.hoursAgo)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download