Assuming I declare
var ad = {};
How can I check whether this object will contain any user-defined properties?
ES6 function
/**
* Returns true if an object is empty.
* @param {*} obj the object to test
* @return {boolean} returns true if object is empty, otherwise returns false
*/
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0
Examples:
let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false
Late answer, but some frameworks handle objects as enumerables. Therefore, bob.js can do it like this:
var objToTest = {};
var propertyCount = bob.collections.extend(objToTest).count();
Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:
var ad = {};
Object.keys(ad).length;//this will be 0 in this case
Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
If you're using underscore.js then you can use the _.isEmpty function:
var obj = {};
var emptyObject = _.isEmpty(obj);