Проверка на пустоту по-человечески на JavaScript
![]()
В работе с js часто можно столкнуться с тем, что ты точно не знаешь пустая переменная или нет, но очень надо по ней пройтись через for или отправить на бэк.
Мы можем проверить массив или текст на длину и узнать, пустой он или нет, но как точно определить массив это или обьект?
Если мы напишем typeof, js ответит нам что и [] и <> обьекты
Для таких случаев я использую функцию проверки на пустоту, учитывая все моменты, которые могут пойти не по сценарию.
Первый пример
Представим, что нам нужно отправить форму на сервер используя js.
Мы знаем, что в форме есть поле имя , фамилия, номер телефона и вопрос.
Поля имя и номер телефона обязательные.
Возьмем простую форму отправки:
Отправка происходит с помощью js, поэтому мы дописываем слушатель на форму
Теперь добавим функцию для проверки на пустоту и разберем ее:
Мы видим, что в функцию isEmpty нам приходят данные, которые мы должны проверить и дать ответ. Мы можем проверять число, текст, объекты и массивы. Если мы передадим undefined, функция также скажет нам, что переменная пустая.
Допишем наш код на js с учетом проверки полей формы
Таким образом, мы сделали простую проверку на поля, которую можем использовать при отправке форм.
Второй пример
Мы получаем некоторые данные из api и должны перезаписать данные, если они обновились.
У нас есть массив, в котором находится список записей
В ответе от сервера у нас может быть как массив так и пустота(также с сервера нам может придти любой ответ, кроме нужного, кто их знает бэкендеров).
Мы получили данные и занесли их в переменную response.
Теперь для того, чтобы проверить, нужно нам перезаписывать переменную или нет, мы можем использовать наш код из примера выше
Таким образом, я или не отправлю пустоту на сервер и скажу пользователю, что именно он не заполнил.
Или не начну перебирать пустую переменную, что точно приведет к ошибке.
Методы объектов JS: Как проверить объект JavaScript на пустоту?
Проверить является ли объект пустым – одна из постоянно встречающихся задач в повседневной жизни Javascript разработчика.
Например, работая над очередной фичей в React приложении, требовалось делать активной кнопку “Подтвердить” только в том случае, когда объект const order = <> содержал свойства, то есть не был пустым.
В случае если бы переменная order содержала массив, то все было бы просто:
Рассмотрим 4 метода объектов js, которые помогут проверить объект на пустоту.
1. Object.keys()
Первый способ — использовать метод Object.keys() для получения нового массива из ключей (свойств) объекта. Если свойства отсутствуют, то новый массив будет пустой.
Тоже самое можно записать так:
Далее прописываем переменную для свойства disabled нашей кнопки (делаем ее неактивной):
2. JSON.stringify()
Второй способ проверить объект на пустоту — использовать метод JSON.stringify() , чтобы перевести наш объект в строчный формат и сравнить результат со строкой '<>' .
Добавляем наше условие:
3. Цикл for..in
Данный способ интересен тем, что его поддерживают более старые версии браузеров. Ознакомиться с текущим состоянием браузерной совместимости цикла for..in можно здесь ).
Давайте создадим функцию, которая принимает на вход объект и использует цикл for..in , чтобы пробежаться по ключам объекта. Далее используем метод object.hasOwnProperty() для проверки наличия ключа.
Функция возвращает true , в случае если ключи отсутствуют. Мы получим значение false , если в объекте присутствует хотя бы один ключ.
4. isEmpty (метод в библиотеке Lodash)
В библиотеке Lodash есть специальный метод, который принимает на вход как массивы так и объекты:
Методы массивов JavaScript (11 методов)
Переменные JavaScript var, let и const (в чем отличие и когда использовать)?
How to Check if an Object is Empty in JavaScript – JS Java isEmpty Equivalent

Joel Olawanle

An object is one of the most commonly used data types in programming. An object is a collection of related data stored as key-value pairs. For example:
When working with objects, you may need to check if an object is empty before performing a function.
In JavaScript, there are various ways you can check if an object is empty. In this article, you will learn the various ways you can do this, the options that can be attached, and why.
Note: An object is considered empty when it has no key-value pair.
In case you are in a rush, here is a basic example:
Both methods will return true . Let’s now understand these and more options you can use to check if an object is empty in JavaScript.
How to Check if an Object is Empty with Object.keys()
The Object.keys() method is a static object method introduced in ECMAScript6 (ES6) and is supported in all modern browsers. This method returns an array with the keys of an object. For example:
With this, you can now apply the .length property. If it returns zero (0), the object is empty.
You can now use this method to check if an object is empty with an if statement or create a function that checks.
This will return either true or false . If the object is empty, it will return true , otherwise, it will return false .
Note: Checking the length alone is not the best option when checking if an object is empty or for any datatype. It is always best to confirm if the data type is correct.
To do this, you can use the constructor check:
This way, you are liable to get a more thorough check.
Thus far, everything has worked fine. But you might also want to avoid throwing a TypeError when a variable is undefined or a value of null is passed instead of <> . To fix this, you can add an extra check:
In the code above, an extra check is added. This means that it will return either null or undefined if it is not an empty object, as shown in the example below:
Note: This applies to other object static methods, meaning you can make use of Object.entries() or Object.values() instead of Object.keys() .
How to Check if an Object is Empty with a for…in Loop
Another method you can use is the ES6 for…in loop. You can use this loop alongside the hasOwnProperty() method.
The method above will loop through each object property. If it finds a single iteration, the object is not empty. Also, the hasOwnProperty() will return a boolean indicating whether the object has the specified property as its property.
How to Check if an Object is Empty with JSON.stringify()
You can also make use of the JSON.stingify() method, which is used to convert a JavaScript value to a JSON string. This means it will convert your object values to a sting of the object. For example:
This means when it is an empty object, then it will return «<>» . You can make use of this to check for an empty object.
This will return true if the object is empty, otherwise false :
How to Check if an Object is Empty with Lodash
Finally, some of the methods I’ve explained here might work for older browser versions, while others may not work. If you are concerned about a solution that will work for both old and modern browser versions, you can use Lodash.
Lodash is a modern JavaScript utility library that can perform many JavaScript functionalities with very basic syntax.
For example, if you want to check if an object is empty, you only need to use the «isEmpty» method.
Installing Lodash into your project is quite easy. All you have to do is make use of this command:
You can now initialize the underscore method and make use of this method.
That’s It!
I’ve enjoyed exploring the various ways you can check if an object is empty. Feel free to use the best method that fits your project or task.
Have fun coding!
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.
How to check if an object is empty in JavaScript
For JavaScript objects, there is no built-in .length or .isEmpty method available to check if they are empty.
Here are 4 different methods that you can use to make sure that a given object does not have its own properties:
The Object.entries() method takes an object as an argument and returns an array of its enumerable property [key, value] pairs.
We can then use the .length property of the array to check if it contains any item:
Note: Object.entries() only works in modern browsers and is not supported by IE. If you need backward compatibility, consider adding a polyfill or use Oject.keys() method instead.
The Object.keys() method is the best way to check if an object is empty because it is supported by almost all browsers, including IE9+.
It returns an array of a given object's own property names. So we can simply check the length of the array afterward:
The Object.getOwnPropertyNames() method takes an object as parameter and returns an array of its own property names:
If you are already using 3rd-party libraries like jQuery or Lodash in your web application, you can also use them to check if an object is empty:
You can write a helper function isEmpty() and add it to the object's prototype:
Now you can call the isEmpty() method on any JavaScript object to check if it has its own properties:
Be careful while extending the Object prototype, as it can cause issues when used together with other JavaScript frameworks. Instead, use the Object.keys() method in JavaScript applications to check if an object is empty.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.