JS objects have a method to get all the keys in the object.
const author = {
firstName: 'Param',
lastName: 'Harrison'
};
console.log(Object.keys(author)); // Output - ["firstName", "lastName"]
To check whether the object is empty or not, you can check the number of keys.
if (Object.keys(author).length === 0) {
console.log('Author object is empty');
} else {
console.log('Author object is not empty');
}
Since we have the keys, it will show Author object is not empty
in the console output.
Now, remove the keys in the object and check,
const author = {};
console.log(Object.keys(author)); // Output - []
It will display Author object is empty
in the console.
JS Mates launched our REST API Design using Node Js course for free, check it out here. It is an interactive text course.
Follow us for more free courses on JavaScript ecosystem on Twitter. Subscribe to our weekly newsletter for more goodies here.
Top comments (0)