2

I have a variable var a = {};

if ( a !==null) {
// Entering here if var a has empty object but i don't want to enter.
}

if (a == null) {
// Want to enter into this condition if var a has empty object.
}

I have tried several ways to write this condition like giving a=={} but it still entering first condition. Could you please let me know the appropriate way to check that condition?

1
  • Thank you all for your valid responses. @Janaka dissanayake response came handy. Commented Nov 11, 2016 at 3:00

4 Answers 4

3

First option

var a = null;

Second option

if ( a !==null && JSON.stringify(a) !== '{}') {..}
Sign up to request clarification or add additional context in comments.

1 Comment

const empty = {} Object.keys(empty).length === 0 && empty.constructor === Object
2

function isEmptyObject(obj) {
  return Object.keys(obj).length == 0;
}

var a = {};

if (isEmptyObject(a)) {
  console.log('emptyOject')
}

2 Comments

What if a is null or undefined? Should test for it in function.
@will Not in a function called isEmptyObject, if you change it to isNullOrEmptyObject() then maybe, but the OP 's example is about an empty object. I have a variable var a = {}; In any case, that's trivial... I'm sure the OP can figure that out.
1

jQuery does

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
}

1 Comment

That's going to check inherited properties too. As long as the OP understands and chooses the one they want.
0

In ECMA script 5

var objInTest = {};

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

Pre ECMA script 5

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

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.