How do I check if a value is an empty object in JavaScript?
Antek N
antek n profile pic

To check if a value is an empty object in JavaScript, you can use several approaches. Here are a few methods you can use: Method 1: Using the Object.keys() method

1
2
3
4
5
6
7
8
9
10
11
12
13
14

function isEmptyObject(value) {
  if (typeof value !== 'object' || Array.isArray(value)) {
    return false;
  }

  return Object.keys(value).length === 0;
}

const obj = {};
console.log(isEmptyObject(obj)); // Output: true

const nonEmptyObj = { key: 'value' };
console.log(isEmptyObject(nonEmptyObj)); // Output: false

This method checks if the value is of type 'object' and not an array. Then it uses the Object.keys() method to get an array of the object's keys and checks if the length of the keys array is zero. Method 2: Using a for...in loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

function isEmptyObject(value) {
  if (typeof value !== 'object' || Array.isArray(value)) {
    return false;
  }

  for (const key in value) {
    if (value.hasOwnProperty(key)) {
      return false;
    }
  }

  return true;
}

const obj = {};
console.log(isEmptyObject(obj)); // Output: true

const nonEmptyObj = { key: 'value' };
console.log(isEmptyObject(nonEmptyObj)); // Output: false

This method iterates over the object's properties using a for...in loop and checks if the object has any own properties. If it finds at least one own property, it returns false; otherwise, it returns true. Method 3: Using JSON.stringify()

1
2
3
4
5
6
7
8
9
10
11
12
13
14

function isEmptyObject(value) {
  if (typeof value !== 'object' || Array.isArray(value)) {
    return false;
  }

  return JSON.stringify(value) === '{}';
}

const obj = {};
console.log(isEmptyObject(obj)); // Output: true

const nonEmptyObj = { key: 'value' };
console.log(isEmptyObject(nonEmptyObj)); // Output: false

This method converts the object to a JSON string using JSON.stringify() and checks if the resulting string is '{}', which represents an empty object in JSON notation. Choose the method that best suits your use case and preferences. All these methods can reliably check if a value is an empty object in JavaScript.