Determining Object Emptiness in JavaScript
JavaScript objects are fundamental data structures, and frequently you'll need to determine if an object is empty before performing operations on it. This challenge focuses on writing a function that accurately checks if a JavaScript object contains any properties. Understanding how to reliably detect empty objects is crucial for writing robust and error-free code.
Problem Description
You are tasked with creating a JavaScript function called isEmpty(obj) that takes a single argument: obj. This argument will be a JavaScript object. The function should return true if the object is empty (i.e., has no own properties) and false otherwise. "Own properties" refer to properties directly defined on the object itself, not inherited from its prototype chain.
Key Requirements:
- The function must correctly identify empty objects.
- The function must handle objects with inherited properties without considering them.
- The function should return a boolean value (
trueorfalse).
Expected Behavior:
- An object created with
{}should returntrue. - An object created with
{ key: 'value' }should returnfalse. - An object inheriting properties from a prototype should return
trueif it has no own properties. nullorundefinedshould be treated as empty objects and returntrue.
Edge Cases to Consider:
- Objects with only inherited properties.
nullandundefinedinputs.- Objects with properties that have
undefinedvalues. - Objects with properties that are empty arrays or empty objects themselves.
Examples
Example 1:
Input: {}
Output: true
Explanation: The object is created with no properties.
Example 2:
Input: { name: 'John', age: 30 }
Output: false
Explanation: The object has two own properties: 'name' and 'age'.
Example 3:
Input: null
Output: true
Explanation: Null is treated as an empty object.
Example 4:
Input: { }.__proto__.property = 'inherited';
Output: true
Explanation: The object has no own properties, only an inherited one.
Example 5:
Input: { key: undefined }
Output: false
Explanation: The object has a property, even if its value is undefined.
Constraints
- The input
objwill always be a JavaScript object,null, orundefined. - The function must execute in O(1) time complexity. Iterating through the object's properties is not acceptable.
- The function should not modify the input object.
Notes
Consider using JavaScript's built-in object properties to efficiently determine if an object is empty. The Object.keys() method can be helpful, but be mindful of the time complexity constraint. Think about properties that are inherent to all JavaScript objects. Remember to handle null and undefined gracefully.