1

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: http://alainwebdesign.ca/pl2/#/petType

javascript:

$scope.setDate = function (dateSelected) {
    alert(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;            
    }
}
Liam
  • 27,717
  • 28
  • 128
  • 190
  • 3
    Possible duplicate of [Detecting an undefined object property](http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) – Liam Oct 11 '16 at 15:09
  • @Liam But that question doesn't have NaN anywhere in it, and that was my main problem –  Oct 11 '16 at 23:10

2 Answers2

2

Your problem is not with your if statement. NaN in Javascript is somewhat special.

For example: NaN === NaN // false

You can read about it more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

Change your check to:

if ($scope.hoursAgo === undefined || isNaN($scope.hoursAgo)) {
...
} else {..}
Liam
  • 27,717
  • 28
  • 128
  • 190
fredrik
  • 17,537
  • 9
  • 51
  • 71
1

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

write like this

if ($scope.hoursAgo === 'undefined' || isNaN($scope.hoursAgo)) {
Nitin Kumar
  • 898
  • 7
  • 22
  • That worked, thank you! I can accept your answer in 5 min. Is that just an AngularJS thing or should NaN always be checked like that? –  Oct 11 '16 at 11:29
  • @Thomas Always in JS. Has nothing to do with Angular. – fredrik Oct 11 '16 at 11:30