F Matheus
F Matheus

Reputation: 25

Verify if object is null Javascript / Angularjs

Here is my code:

function getMelhorBloco(tamanho){

    var blocoMelhor = {};
    var testeEntrouBloco = true;

            for(var i = 0; i < $scope.blocos.length; i++) {
                if($scope.blocos[i].estado == "Livre") {

                    if(tamanho < $scope.blocos[i].tamanhoTotal) {
                        if(testeEntrouBloco) {
                            blocoMelhor.indice = $scope.blocos[i].idBloco;
                            blocoMelhor.tamanho = $scope.blocos[i].tamanhoTotal;
                            testeEntrouBloco = false;
                        } else {
                            if($scope.blocos[i].tamanhoTotal < blocoMelhor.tamanho) {
                                blocoMelhor.indice = $scope.blocos[i].idBloco;
                                blocoMelhor.tamanho = $scope.blocos[i].tamanhoTotal;

                            }
                        }
                    }
            }
        }

    return blocoMelhor;
}

I was trying to check if my object "blocoMelhor" is null.

I tried

if(blocoMelhor == null){} 
if(blocoMelhor == undefined){} 
if(blocoMelhor ===null){} 

and the method:

function isEmpty(obj){
    for(var key in obj) {
        if(obj.hasOwnProperty(key)){
            return false;
        }
        return true;
    }
}

I printed the value of "blocoMelhor" and the console gives me this: Object { }

Any suggestions?

Upvotes: 0

Views: 74

Answers (3)

F Matheus
F Matheus

Reputation: 25

i made the verification with the attributes of object and works:

var returnOfGetMelhorBloco = getMelhorBloco(tamanho);
if(returnOfGetMelhorBloco.indice == undefined){
//the object is null
} else {
//the object is not null
}

Upvotes: 0

alvarosps
alvarosps

Reputation: 83

have you tried to use something like

if (!blocoMelhor){ //do something } 

? it's the best way, I think.

Upvotes: 0

Jahirul Islam Bhuiyan
Jahirul Islam Bhuiyan

Reputation: 799

try following

var blocoMelhor;

if(!blocoMelhor){ 
do something for null
} 

initialization by {} means you create a object

Upvotes: 1

Related Questions