I am using javascript sort function on angular scope inside an if condition. My condition is false still it is going inside <p>Here is the code snippet:</p> <pre><code>$scope.notes = notes.data; if($scope.notes) { console.log("notes", $scope.notes); } else { console.log("no notes"); } if($scope.notes) { console.log("in this if"); $scope.singleNote = $scope.notes.sort(function(a,b) { return new Date(b.date_posted).getTime() - new Date(a.date_posted).getTime() })[0]; } </code></pre> <p>Even if the logic goes in else, it is also going in the 2nd if. It does not display the console of 2nd if but gives an error called: $scope.notes.function is not defined. It should not go in the 2nd if, if it goes in the else block.</p>