-1

Before you look past this question, I know exactly what is causing this error and why. I've got an object and I'm effectively testing to see if it's empty by checking it's length; when the array is empty, it causes roughly 30 errors per $scope.$on('$ionicView.enter') call.

Is there a way to stop these errors from being thrown constantly/is there a better way to test if an array is filled with something?

JS:

$scope.checkLeague = function () {
        if ($scope.favs.length > 0){
            return false;
        }
        return true;
    };

Error:

null is not an object (evaluating '$scope.favs.length')

Edit: Having looked further into the problem, $scope.favs is initialised as null to try and combat this error, but is being set as an empty array later in the code, as this is a REST response. The problem still lies in successfully catching an array that will always be instantiated but maybe empty. Logging the array to the console will always produce [].

Tom Sykes
  • 161
  • 2
  • 14

3 Answers3

0

Try to check $scope.favs value before:

$scope.checkLeague = function () {
        if ($scope.favs && $scope.favs.length > 0){
            return false;
        }
        return true;
    };
0

You could try something like this:

$scope.checkLeague = function () {
    if ($scope.favs.hasOwnProperty("length") && $scope.favs.length > 0){
        return false;
    }
    return true;
};
0

A length property with "0" or null value doesn't necessarily mean that the object is empty. Check this up

var a = [1,2,3,4];
a.key1 = "test";
a.length; // <- 4
Object.keys(a); // <- ["0", "1", "2", "3", "key1"]
a.length = null;
a; // <- [];
Object.keys(a); // <- ["key1"]
Object.getOwnPropertyNames(a); // <- ["length", "key1"]

you might need to check the Object.keys().length

Redu
  • 25,060
  • 6
  • 56
  • 76
  • Unfortunately, all I'm getting is `Error: null is not an object (evaluating 'Object.keys($scope.favs)')` – Tom Sykes May 05 '16 at 16:18
  • Obviously there is no such a `favs` thing. You might consider having a look at http://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object – Redu May 05 '16 at 16:24