The empty object is undefined, like this var empty_obj = {}
.
An undefined will be a false one. But I notice that empty_obj || 3
will return empty_obj
not 3
.
Why is that?
The empty object is not undefined.
console.log({} === undefined); // false console.log(typeof {}); // object
It is a truthy value:
if ({}) console.log('truthy'); // truthy
It even has some properties:
console.log(typeof {}.hasOwnProperty); // function
The only falsy values in JS are 0
, false
, null
, undefined
, empty string, and NaN
.
You may be confused by the return value of var =
statements. These will always show as undefined
in the Chrome console:
> var obj = {} undefined > var x = 100 undefined > var y = "potato" undefined
Just because the var =
statement returns undefined doesn't mean the value was undefined. Although, without the var
, assignments do return the value being assigned:
> obj = {} {} > x = 100 100 > y = "potato" "potato"
As mentioned in above answers empty object is not falsy value in JavaScript,
how to check if obj is empty correctly?
Object.keys(obj).length === 0 && obj.constructor === Object
Why do we need an additional constructor check?
You may be wondering why do we need the constructor check. Well, it's to cover for the wrapper instances. In JavaScript, we have 9 built-in constructors.
new String(); new Number(); new Boolean(); new Array(); new RegExp(); new Function(); new Date();
So we can create an empty object with new Object(). Side note: you should NEVER create an object using the constructor. It's considered bad practice.
const obj = new Object(); Object.keys(obj).length === 0; // true
So just using the Object.keys, it does return true when the object is empty. But doesn't work when we create a new object instance using these other constructors
Object.keys(new String()).length === 0 // false
hence constructor check is necessary for object instance
function isEmptyObj(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object; } console.log(isEmptyObj({}));
P.S
this snippet only works for objects don't use for undefined or null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With