Is Empty in JavaScript?

If you’re wondering whether the “is empty” function in JavaScript returns true for objects, the answer is no. In this blog post, we’ll explain why and show you how to check if an object is empty in JavaScript.

Checkout this video:

Introduction

The isEmpty() function in JavaScript checks whether an object is empty or not. An object is considered empty if it has no own enumerable properties.

In order to check if an object is empty in JavaScript, you can use the Object.keys() method. This method returns an array of the object’s own enumerable properties.

If the array is empty, then the object is empty.

What is Empty in JavaScript?

In JavaScript, empty values can be represented by null, undefined, or an empty string. An empty string is a string with zero characters. This section will discuss how to check if a variable is empty in JavaScript.

The null value

In JavaScript, the empty value can be represented by null, undefined, or an empty string “”. These three things are not the same.

The null value

The null value is a primitive value that represents the absence of a value. It is important to understand that null is not the same as undefined.

Null values are assigned using the null keyword:
“`javascript
let x = null;
“`
You can also use the null keyword to test whether a variable has a value:
“`javascript
if (x == null) { … } // true if x is undefined OR null
if (x === null) { … } // true only if x isnull
“`

The undefined value

The undefined value is a primitive value automatically assigned to variables that have not been initialized:

“`javascript

The undefined value

The undefined value is returned when a variable that has not been assigned a value is accessed.

We can test for undefined with the typeof operator:

if (typeof variable === “undefined”) {
// do something
}

The empty string

In JavaScript, an empty string is a string of zero length, represented as “” or ”.

An empty string is falsey, which means it is considered false when converted to a Boolean. However, an empty string is truthy, which means it is considered true when converted to a Boolean.

An empty string has a length of 0.

Conclusion

Boolean(), the logical negation operator (!), and the double-negation operator (!!) all can be used to convert a value to its corresponding Boolean value. However, they do so in slightly different ways:

Boolean() performs an explicit conversion of any value to a Boolean.
! performs an implicit conversion of any value to a Boolean then negates it.
!! performs an implicit conversion of any value to a Boolean then negates it twice, effectively converting it back to its original non-Boolean state.

Scroll to Top