You can use a forโฆin loop with an Object.hasOwn (ECMA 2022+) test to check whether an object has any own properties:
function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}
If you also need to distinguish {}-like empty objects from other objects with no own properties (e.g. Dates), you can do various (and unfortunately need-specific) type checks:
function isEmptyObject(value) {
if (value == null) {
// null or undefined
return false;
}
if (typeof value !== 'object') {
// boolean, number, string, function, etc.
return false;
}
const proto = Object.getPrototypeOf(value);
// consider `Object.create(null)`, commonly used as a safe map
// before `Map` support, an empty object as well as `{}`
if (proto !== null && proto !== Object.prototype) {
return false;
}
return isEmpty(value);
}
Note that comparing against Object.prototype like in this example will fail to recognize cross-realm objects.
Do not use Object.keys(obj).length. It is O(N) complexity because it creates an array containing all the property names only to get the length of that array. Iterating over the object accomplishes the same goal but is O(1).
For compatibility with JavaScript engines that donโt support ES 2022+, const can be replaced with var and Object.hasOwn with Object.prototype.hasOwnProperty.call:
function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true
}
Many popular libraries also provide functions to check for empty objects:
jQuery:
jQuery.isEmptyObject({}); // true
lodash:
_.isEmpty({}); // true
Underscore:
_.isEmpty({}); // true
Hoek:
Hoek.deepEqual({}, {}); // true
ExtJS:
Ext.Object.isEmpty({}); // true
AngularJS (version 1):
angular.equals({}, {}); // true
Ramda:
R.isEmpty({}); // true
You can use a forโฆin loop with an Object.hasOwn (ECMA 2022+) test to check whether an object has any own properties:
function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}
If you also need to distinguish {}-like empty objects from other objects with no own properties (e.g. Dates), you can do various (and unfortunately need-specific) type checks:
function isEmptyObject(value) {
if (value == null) {
// null or undefined
return false;
}
if (typeof value !== 'object') {
// boolean, number, string, function, etc.
return false;
}
const proto = Object.getPrototypeOf(value);
// consider `Object.create(null)`, commonly used as a safe map
// before `Map` support, an empty object as well as `{}`
if (proto !== null && proto !== Object.prototype) {
return false;
}
return isEmpty(value);
}
Note that comparing against Object.prototype like in this example will fail to recognize cross-realm objects.
Do not use Object.keys(obj).length. It is O(N) complexity because it creates an array containing all the property names only to get the length of that array. Iterating over the object accomplishes the same goal but is O(1).
For compatibility with JavaScript engines that donโt support ES 2022+, const can be replaced with var and Object.hasOwn with Object.prototype.hasOwnProperty.call:
function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true
}
Many popular libraries also provide functions to check for empty objects:
jQuery:
jQuery.isEmptyObject({}); // true
lodash:
_.isEmpty({}); // true
Underscore:
_.isEmpty({}); // true
Hoek:
Hoek.deepEqual({}, {}); // true
ExtJS:
Ext.Object.isEmpty({}); // true
AngularJS (version 1):
angular.equals({}, {}); // true
Ramda:
R.isEmpty({}); // true
If ECMAScript 5 support is available, you can use Object.keys():
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
For ES3 and older, there's no easy way to do this. You'll have to loop over the properties explicitly:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
You can just check if the variable has a truthy value or not. That means
if (value) {
// do something..
}
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.
This question has two interpretations:
Check if the variable has a value
Check if the variable has a truthy valueThe following answers both.
In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:
โญโ nullish โโโโโโโฎ โญโ not nullish โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโฌโโโโฌโโโโโฌโโโโโโฌโโโโโโโฌโโโโฌโโโโโโโโโโฌโโโโโโ
โ undefined โ null โ false โ 0 โ "" โ ... โ true โ 1 โ "hello" โ ... โ
โโโโโโโโโโโโโดโโโโโโโดโโโโโโโโดโโโโดโโโโโดโโโโโโดโโโโโโโดโโโโดโโโโโโโโโโดโโโโโโ
โฐโ falsy โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โฐโ truthy โโโโโโโโโโโโโโโโฏ
Check if value is nullish (undefined or null)
Use one of the following depending on your coding style:
if (value == null) { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined) { /* value is nullish */ }
if ((value ?? null) === null) { /* value is nullish */ }
Notes:
- The
==operator works because it has a special case for null vs undefined comparison - The
===operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately - The first and third examples work identically, however the third one is rarely seen in production code
- The fourth example uses nullish coalescing operator to change nullish values to
nullfor straight forward comparison
Check if value is not nullish
if (value != null) { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined) { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null) { /* value is not nullish, although it could be falsy */ }
Check if value is falsy
Use the ! operator:
if (!value) { /* value is falsy */ }
Check if value is truthy
if (value) { /* value is truthy */ }
Data validation
The nullish, falsy and truthy checks cannot be used for data validation on their own. For example, 0 (falsy) is valid age of a person and -1 (truthy) is not. Additional logic needs to be added on case-by-case basis. Some examples:
/*
* check if value is greater than/equal to 0
* note that we cannot use truthy check here because 0 must be allowed
*/
[null, -1, 0, 1].forEach(num => {
if (num != null && num >= 0) {
console.log("%o is not nullish and greater than/equal to 0", num);
} else {
console.log("%o is bad", num);
}
});
/*
* check if value is not empty-or-whitespace string
*/
[null, "", " ", "hello"].forEach(str => {
if (str && /\S/.test(str)) {
console.log("%o is truthy and has non-whitespace characters", str);
} else {
console.log("%o is bad", str);
}
});
/*
* check if value is not an empty array
* check for truthy before checking the length property
*/
[null, [], [1]].forEach(arr => {
if (arr && arr.length) {
console.log("%o is truthy and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
/*
* check if value is not an empty array
* using optional chaining operator to make sure that the value is not nullish
*/
[null, [], [1]].forEach(arr => {
if (arr?.length) {
console.log("%o is not nullish and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
Videos
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined is true, the above code will catch both null and undefined.
The standard way to catch null and undefined simultaneously is this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.
Edit again
The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over.
You should not have any references to undeclared variables in your code.
I don't think you can make that any simpler, but you could certainly refactor that logic into a function:
function isRealValue(obj)
{
return obj && obj !== 'null' && obj !== 'undefined';
}
Then, at least your code becomes:
if (isRealValue(yourObject))
{
doSomething();
}
If you have jQuery, you could use $.isEmptyObject().
$.isEmptyObject(null)
$.isEmptyObject(undefined)
var obj = {}
$.isEmptyObject(obj)
All these calls will return true. Hope it helps
Hi everyone,
I very often find myself writing something like
if( Object.keys(someObject).length > 0 ) {
//do some wild stuff
}
To check if a basic object is empty or not i.e. not {} there must be a beautiful way.
I know lodash and jQuery have their solutions, but I don't want to import libraries for a single method, so I'm about to write a function to use across a whole project, but before I do that I want to know I'm not doing something really stupid that ES6/ES7/ES8 can do that I'm just not aware of.
edit solution courtesy of u/vestedfox
Import https://www.npmjs.com/package/lodash.isequal
Total weight added to project after compilation: 355 bytes
Steps to achieve this.
npm i --save lodash.isequal
then somewhere in your code
const isEqual = require('lodash.isequal');
If you're using VueJS and don't want to have to include this in every component and don't want to pollute your global namespace you can do this in app.js
const isEqual = require('lodash.isequal');
Vue.mixin({
methods: {
isEqual: isEqual
}
});Then in your components you can simply write.
if( this.isEqual(someObject, {})) {
console.log('This object has properties');
}