Skip to content

Commit 0983882

Browse files
committed
exec: how-do-you-reliably-determine-whether-an-object-is-empty
1 parent 4b75530 commit 0983882

File tree

1 file changed

+8
-5
lines changed
  • questions/how-do-you-reliably-determine-whether-an-object-is-empty

1 file changed

+8
-5
lines changed

questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ title: How do you reliably determine whether an object is empty?
66

77
To reliably determine whether an object is empty, you can use `Object.keys()` to check if the object has any enumerable properties. If the length of the array returned by `Object.keys()` is zero, the object is empty.
88

9-
```js
9+
```js live
1010
const isEmpty = (obj) => Object.keys(obj).length === 0;
1111

1212
const obj = {};
@@ -21,7 +21,7 @@ console.log(isEmpty(obj)); // true
2121

2222
The most common and reliable way to check if an object is empty is by using `Object.keys()`. This method returns an array of the object's own enumerable property names. If the length of this array is zero, the object is empty.
2323

24-
```js
24+
```js live
2525
const isEmpty = (obj) => Object.keys(obj).length === 0;
2626

2727
const obj1 = {};
@@ -35,7 +35,7 @@ console.log(isEmpty(obj2)); // false
3535

3636
Another method is to use `Object.entries()`, which returns an array of the object's own enumerable property `[key, value]` pairs. If the length of this array is zero, the object is empty.
3737

38-
```js
38+
```js live
3939
const isEmpty = (obj) => Object.entries(obj).length === 0;
4040

4141
const obj1 = {};
@@ -49,7 +49,7 @@ console.log(isEmpty(obj2)); // false
4949

5050
Similarly, you can use `Object.values()`, which returns an array of the object's own enumerable property values. If the length of this array is zero, the object is empty.
5151

52-
```js
52+
```js live
5353
const isEmpty = (obj) => Object.values(obj).length === 0;
5454

5555
const obj1 = {};
@@ -63,7 +63,7 @@ console.log(isEmpty(obj2)); // false
6363

6464
You can also use a `for...in` loop to check if an object has any properties. If the loop doesn't iterate over any properties, the object is empty.
6565

66-
```js
66+
```js live
6767
const isEmpty = (obj) => {
6868
for (let key in obj) {
6969
if (obj.hasOwnProperty(key)) {
@@ -75,9 +75,12 @@ const isEmpty = (obj) => {
7575

7676
const obj1 = {};
7777
const obj2 = { key: 'value' };
78+
const childObj = Object.create(obj2); // Inherit from obj2
7879

7980
console.log(isEmpty(obj1)); // true
8081
console.log(isEmpty(obj2)); // false
82+
console.log(isEmpty(childObj)); // true (has no own properties)
83+
console.log(childObj.key); // Output: 'value' (still has the inherited property)
8184
```
8285

8386
### Edge cases

0 commit comments

Comments
 (0)