JS Coding Questions Logo
JS Coding Questions
#128💼 Interview💻 Code

How do you test for an empty object

Advertisement

728x90

There are different solutions based on ECMAScript versions

1. Using Object entries(ECMA 7+): You can use object entries length along with constructor type.

javascript
1Object.entries(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well

2. Using Object keys(ECMA 5+): You can use object keys length along with constructor type.

javascript
1Object.keys(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well

3. Using for-in with hasOwnProperty(Pre-ECMA 5): You can use a for-in loop along with hasOwnProperty.

javascript
1function isEmpty(obj) {
2  for (var prop in obj) {
3  if (obj.hasOwnProperty(prop)) {
4  return false;
5  }
6  }
7
8  return JSON.stringify(obj) === JSON.stringify({});
9  }

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 44

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
128of476