Is Object Empty
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an object or an array, return if it is empty.
- An empty object contains no key-value pairs.
- An empty array contains no elements.
You may assume the object or array is the output of JSON.parse.
Examples
Example 1
Input: obj = {"x": 5, "y": 42}
Output: false
Explanation: The object has 2 key-value pairs so it is not empty.
Example 2
Input: obj = {}
Output: true
Explanation: The object doesn't have any key-value pairs so it is empty.
Example 3
Input: obj = [null, false, 0]
Output: false
Explanation: The array has 3 elements so it is not empty.
Constraints
objis a valid JSON object or array2 <= JSON.stringify(obj).length <= 10^5
Can you solve it in O(1) time?
Solution
Method 1 – Type and Length Check
Intuition
To check if an object or array is empty, we can use Object.keys for objects and check the length property for arrays. Both are outputs of JSON.parse, so we don't need to handle other types.
Approach
- If the input is an array, return true if its length is 0.
- If the input is an object, return true if it has no own enumerable properties.
- Otherwise, return false.
Code
JavaScript
function isEmpty(obj) {
if (Array.isArray(obj)) return obj.length === 0;
return Object.keys(obj).length === 0;
}
TypeScript
function isEmpty(obj: any): boolean {
if (Array.isArray(obj)) return obj.length === 0;
return Object.keys(obj).length === 0;
}
Complexity
- ⏰ Time complexity:
O(n)— n is the number of keys for objects or elements for arrays (forObject.keysorlength). - 🧺 Space complexity:
O(n)— For the array returned byObject.keys(for objects).