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

Summarize some general principles of web design and production

<br />Related articles: 9 practical suggesti...

Vue+node realizes audio recording and playback function

Result: The main part is to implement the code lo...

Detailed explanation of three methods of JS interception string

JS provides three methods for intercepting string...

Tips for implementing multiple borders in CSS

1. Multiple borders[1] Background: box-shadow, ou...

Two ideas for implementing database horizontal segmentation

introduction With the widespread popularity of In...

Forty-nine JavaScript tips and tricks

Table of contents 1. Operation of js integer 2. R...

impress.js presentation layer framework (demonstration tool) - first experience

I haven’t blogged for half a year, which I feel a ...

Centos builds chrony time synchronization server process diagram

My environment: 3 centos7.5 1804 master 192.168.1...

MySQL optimization: use join instead of subquery

Use JOIN instead of sub-queries MySQL supports SQ...

CSS delivery address parallelogram line style example code

The code looks like this: // Line style of the pa...

Detailed explanation of the steps to create a web server with node.js

Preface It is very simple to create a server in n...

Rainbow button style made with CSS3

Result: Implementation code: html <div class=&...