Example implementation of checking whether an object is empty in native javascript

Example implementation of checking whether an object is empty in native javascript

Below is the code snippet to check if an object is null. For newer browsers, you can use ES6's "Object.keys". For older browsers, you can install the Lodash library and use its "isEmpty" method.

const empty = {}; 
/* -------------------------
  Newer browsers----------------------------*/
Object.keys(empty).length === 0 && empty.constructor === Object
// true 
/* -------------------------
  Lodash can be used for older browsers
----------------------------*/
_.isEmpty(empty)
// true

What is native JavaScript

Native JavaScript means no frameworks or libraries are used. It’s just regular vanilla JavaScript, no libraries like Lodash or jQuery are used.

A. Checking for null objects in newer browsers

We can check for null objects using the built-in Object.keys method.

const empty = {}; 
Object.keys(empty).length === 0 && empty.constructor === object;

Why do we need additional constructor checks?

You might be wondering why we need to check constructor at all. It is meant to override the wrapper instance. In JavaScript, we have 9 built-in constructors.

new Object();
new String();
new Number();
new Boolean();
new Array();
new RegExp();
new Function();
new Date();

Here, we can create an empty object using new Object() .

const obj = new Object(); 
Object.keys(obj).length === 0; // true

So just use Object.keys , it will indeed return true when the object is empty. But what happens when we create new object instances using other constructors.

function badEmptyCheck(value) {
  return Object.keys(value).length === 0;
} 
badEmptyCheck(new String()); // true 
badEmptyCheck(new Number()); // true 
badEmptyCheck(new Boolean()); // true 
badEmptyCheck(new Array()); // true 
badEmptyCheck(new RegExp()); // true 
badEmptyCheck(new Function()); // true 
badEmptyCheck(new Date()); // true

Solve false positives by checking the constructor

Correct this error by adding a constructor check.

function goodEmptyCheck(value) {
  Object.keys(value).length === 0
    && value.constructor === Object; // constructor check
}
goodEmptyCheck(new String()); // false 
goodEmptyCheck(new Number()); // false 
goodEmptyCheck(new Boolean()); // false 
goodEmptyCheck(new Array()); // false 
goodEmptyCheck(new RegExp()); // false 
goodEmptyCheck(new Function()); // false 
goodEmptyCheck(new Date()); // false

Null check on other values

Next, let's test our method with some values ​​to see what we get.

function isEmptyObject(value) {
  return Object.keys(value).length === 0 && value.constructor === Object;
}

So far so good, for non-objects it returns false .

isEmptyObject(100) // false
isEmptyObject(true) // false
isEmptyObject([]) // false

But be careful! The following values ​​will cause an error.

// TypeError: Cannot covert undefined or null to object
isEmptyObject(undefined);
isEmptyObject(null);

Improved empty checks for null and undefined

If you don't want it to throw TypeError , you can add an extra check

function isEmptyObject(value) {
  return value && Object.keys(value).length === 0 && value.constructor === Object;
}

B. Null object check in older browsers

What if you need to support older browsers? As we all know, when we say old browsers, we mean IE, and we have 2 choices, use native or use libraries.

Checking for null objects using JavaScript

Native JS is not that concise, but it is no problem to judge it as an empty object.

function isObjectEmpty(value) {
  return (
    Object.prototype.toString.call(value) === '[object Object]' && JSON.stringify(value) === '{}'
  );
}

For objects, it returns true .

isObjectEmpty({}); // true 
isObjectEmpty(new Object()); // true

Other types of constructors can also be judged normally

isObjectEmpty(new String()); // false 
isObjectEmpty(new Number()); // false 
isObjectEmpty(new Boolean()); // false 
isObjectEmpty(new Array()); // false 
isObjectEmpty(new RegExp()); // false 
isObjectEmpty(new Function()); // false 
isObjectEmpty(new Date()); // false

Passing null and undefined will not report TypeError .

isObjectEmpty(null); // false
isObjectEmpty(undefined); // false

Checking for null objects using external library

There are a ton of external libraries out there that can be used to check for null objects. And most have good support for older browsers

Lodash 
_.isEmpty({});
// true
Underscore
_.isEmpty({});
// true
jQuery 
jQuery.isEmptyObject({});
// true

Native vs. Library

The answer is it depends! I'm a big fan of keeping my programs as simple as possible because I don't like the overhead of external libraries. Also, for smaller applications I'm too lazy to set up external libraries.

But if your application already has an external library installed, then go ahead and use it. You will know your application better than anyone else. So choose the method that best suits your situation.

The above is the details of the example implementation of checking whether an object is empty in native javascript. For more information about checking whether an object is empty in javascript, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Three ways to determine whether an object is empty in js
  • 5 ways to determine whether an object is an empty object in JS
  • JS/Jquery method to determine whether the object is empty
  • JavaScript Simple Method to Determine if an Object {} is an Empty Object

<<:  The difference between where and on in MySQL and when to use them

>>:  Use of CSS3's focus-within selector

Recommend

How does MySQL ensure master-slave consistency?

Table of contents The basic principle of MySQL ma...

Detailed usage of Vue timer

This article example shares the specific code of ...

Issues with upgrading Python and installing Mongodb drivers under Centos

Check the Python version python -V If it is below...

Web design skills: iframe adaptive height problem

Maybe some people have not come across this issue ...

Discussion on the way to open website hyperlinks

A new window opens. Advantages: When the user cli...

W3C Tutorial (1): Understanding W3C

W3C, an organization founded in 1994, aims to unl...

How to Run a Command at a Specific Time in Linux

The other day I was using rsync to transfer a lar...

Mini Program to Implement Slider Effect

This article example shares the specific code for...

XHTML Basic 1.1, a mobile web markup language recommended by W3C

W3C recently released two standards, namely "...

Detailed analysis of each stage of nginx's http request processing

When writing the HTTP module of nginx, it is nece...

Solution to Navicat Premier remote connection to MySQL error 10038

Remote connection to MySQL fails, there may be th...

How to use IDEA to create a web project and publish it to tomcat

Table of contents Web Development 1. Overview of ...

Win32 MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...