[Easy] LeetCode JS 30 - 2727. Is Object Empty

March 7, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2727. Is Object Empty

Question Prompt

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.

// 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.

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

First, define a isEmpty function. Within the function is the core of the logic.

Since we need to check if the object is empty, we can first use Object.keys(obj) . It converts the properties (or keys) of the input object obj into an array. For example, if you pass in an object like { name: 'Alice' }Object.keys(obj) would give you an array ['name'].

Then, the .length tells us how many elements are in the array. With the length, we can compare the length of the keys array to zero. The function returns true if the array has zero elements (meaning the object was empty), and it returns false otherwise.

var isEmpty = function (obj) {
  return Object.keys(obj).length === 0;
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee