0

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?

3
  • 1
    Why would you think that your object would be null? You're initializing it to {} - that's an empty object, but it's definitely not null or undefined. Commented May 13, 2016 at 17:52
  • isEmpty(obj) will never return false because keys in obj gets a list of keys, meaning that the object MUST contain each one Commented May 13, 2016 at 17:53
  • 1
    Possible duplicate of How do I test for an empty JavaScript object? Commented May 13, 2016 at 17:56

3 Answers 3

1

try following

var blocoMelhor;

if(!blocoMelhor){ 
do something for null
} 

initialization by {} means you create a object

Sign up to request clarification or add additional context in comments.

Comments

0

have you tried to use something like

if (!blocoMelhor){ //do something } 

? it's the best way, I think.

1 Comment

{} will return true;
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.