Contents
In this post, we’ll take a look at how to check if an array is empty in JavaScript. We’ll also explore a few other ways to check if an object is empty.
Checkout this video:
Introduction
In programming, we often need to know if an object or variable is empty. For example, we might want to check if a object has any properties, or if a string contains any characters.
In JavaScript, there are many ways to check if an object or variable is empty. In this article, we’ll discuss some of the most common ways to check for emptiness in JavaScript.
What is empty in JavaScript?
In JavaScript, an empty array can be created by simply creating a new Array():
var myArray = new Array();
myArray.length; // 0
Itβs important to note that if you create an array with the brackets syntax ([]), it will not be empty:
var myArray = [];
myArray.length; // 0
Why is empty in JavaScript?
Some developers may coding in JavaScript like this `if (!variable)`. And they will get false positive when the variable is 0, an empty string, or false. So we need to use `if (variable === null || variable === undefined || variable === ” || variable === false)`.
How to check if a variable is empty in JavaScript?
There are many ways to check if a variable is empty in JavaScript. The most common way is to use the typeof operator:
if (typeof myVariable === “undefined”) {
// myVariable is empty
}
Other ways to check if a variable is empty are outlined below.
Check if a variable is an empty object:
if (jQuery.isEmptyObject(myVariable)) {
// myVariable is empty
}
Check if a variable is null:
if (myVariable === null) {
// myVariable is empty
}
Check if a string contains only whitespace characters:
if (/^\s*$/.test(myVariable)) {
// myVariable is empty or contains only whitespace characters
}
Conclusion
Use the singleton method isEmpty to detect whether an object has any own enumerable string keyed properties.
Returns true if the given object is an empty object, a falsey primitive value, or an instance of a class with no own enumerable properties other than symbols.