3

Empty Objects are Truthy in JavaScript?

 2 years ago
source link: https://masteringjs.io/tutorials/fundamentals/empty-object-truthy
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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');
}

More Fundamentals Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK