How to Test For an Empty Object in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the Object.keys()
Method
You can simply use the Object.keys()
method along with the typeof
operator to test for an empty JavaScript object (contains no enumerable properties). Also, since null == undefined
is true
, obj != null
will catch both null and undefined values.
The isEmptyObject()
function in the following example will check if an object is empty. However, it will only test plain objects (created using "{}
" or "new Object()
").
Example
Try this code »// Defining a function
function isEmptyObject(obj) {
if(typeof obj === 'object' && obj != null && Object.keys(obj).length !== 0){
return false;
} else {
return true;
}
}
// Testing few values
console.log(isEmptyObject({})); // Prints: true
console.log(isEmptyObject({name: "Harry", age: 18})); // Prints: false
console.log(isEmptyObject(null)); // Prints: true
console.log(isEmptyObject(undefined)); // Prints: true
If you're using jQuery you can simply use the jQuery.isEmptyObject()
method to check if an object is empty. Let's try out an example to understand how it basically works:
Example
Try this code »// Testing few values
console.log(jQuery.isEmptyObject({})); // Prints: true
console.log(jQuery.isEmptyObject({name: "Harry", age: 18})); // Prints: false
console.log(jQuery.isEmptyObject(null)); // Prints: true
console.log(jQuery.isEmptyObject(undefined)); // Prints: true
See the tutorial on JavaScript Objects to learn more about creating and manipulating objects.
Related FAQ
Here are some more FAQ related to this topic: