Tutorialspoint
Problem
Solution
Submissions

Check if Object is Empty

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript function to determine if a given object is empty. An empty object is one that has no enumerable properties. The function should return true if the object is empty, and false otherwise.

Example 1
  • Input: obj = {}
  • Output: true
  • Explanation:
    • The input object {} has no properties.
    • Object.keys() returns an empty array [].
    • The length of empty array is 0.
    • Since length is 0, the object is empty.
    • Therefore, the function returns true.
Example 2
  • Input: obj = {name: "John", age: 25}
  • Output: false
  • Explanation:
    • The input object has two properties: "name" and "age".
    • Object.keys() returns ["name", "age"].
    • The length of this array is 2.
    • Since length is greater than 0, the object is not empty.
    • Therefore, the function returns false.
Constraints
  • The input will always be a valid object
  • Consider only enumerable properties
  • Nested objects should be treated as properties
  • Time Complexity: O(1) average case, O(n) worst case where n is number of properties
  • Space Complexity: O(n) for storing keys array
ArraysKPMGPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Object.keys() method to get all enumerable property names
  • Check the length of the returned array
  • If length is 0, the object is empty
  • Alternative approach: use Object.getOwnPropertyNames() for all properties
  • Consider using for...in loop as another approach
  • Handle null and undefined cases if needed

Steps to solve by this approach:

 Step 1: Use Object.keys() method to extract all enumerable property names from the object.
 Step 2: Object.keys() returns an array containing all the property names.
 Step 3: Check the length property of the returned array.
 Step 4: If the length equals 0, it means no properties exist.
 Step 5: Return true if length is 0 (empty object), false otherwise.
 Step 6: This approach works for all types of property values including arrays, objects, and primitives.

Submitted Code :