Empty Objects are Truthy in JavaScript?
May 5, 2022
There are only seven values that are falsy in JavaScript, and empty objects are not one of them.
An empty object is an object that has no properties of its own.
You can use the Object.keys()
function to check if an object is empty as shown below.
if ({}) {
console.log('I will print');
}
if (Object.keys({}).length === 0) {
console.log('I will not print');
}
Handling null
with Object.keys()
JavaScript throws an error if you call Object.keys()
with a null or undefined value.
To work around this, you should check beforehand if the argument being passed is null.
const value = null;
if (typeof value === 'object' && value != null && Object.keys(value).length == 0) {
console.log('I will not print and not throw an error either');
}
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!