Is Object Empty - Problem

Given an object or an array, return true if it is empty, false otherwise.

Definition of 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.

Input & Output

Example 1 — Empty Object
$ Input: obj = {}
Output: true
💡 Note: The object has no key-value pairs, so it's empty and we return true
Example 2 — Non-empty Array
$ Input: obj = [null, false, 0]
Output: false
💡 Note: The array contains elements (even though they're falsy values), so it's not empty
Example 3 — Empty Array
$ Input: obj = []
Output: true
💡 Note: The array contains no elements, so it's empty and we return true

Constraints

  • obj is a valid JSON object or array
  • 2 ≤ JSON.stringify(obj).length ≤ 105

Visualization

Tap to expand
Is Object Empty - Built-in Methods INPUT obj = { } Empty Object No key-value pairs Input Value: {} Type: Object Result of JSON.parse() JSON.parse("{}") ALGORITHM STEPS 1 Check Type Is it Array or Object? 2 For Arrays Check arr.length === 0 3 For Objects Use Object.keys(obj) 4 Return Result keys.length === 0 // Built-in method Object.keys(obj) // Returns: [] [].length === 0 // true FINAL RESULT Object.keys({}) = [ ] Empty array (length: 0) Output: true OK - Empty! The object has no key-value pairs Key Insight: Object.keys() returns an array of property names. For empty objects, it returns []. For arrays, use Array.isArray() to check type first, then check .length property directly. TutorialsPoint - Is Object Empty | Built-in Methods Approach
Asked in
Google 15 Microsoft 12 Amazon 8
35.7K Views
Medium Frequency
~5 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen