How to check if an array is empty or not in JavaScript

We can check if one JavaScript array is empty or not by using its length property. This property returns the number of elements in an array. If its value is 0, that means the array is empty. If it is not, it is not empty.

Different examples to check if an array is empty :

let arr1 = ["a", "b", "c"];
let arr2 = undefined;
let arr3 = null;
let arr4 = [];

if (arr1 && arr1.length) {
  console.log("arr1 is not empty");
} else {
  console.log("arr1 is empty");

if (arr2 && arr2.length) {
  console.log("arr2 is not empty");
} else {
  console.log("arr2 is empty");

if (arr3 && arr3.length) {
  console.log("arr3 is not empty");
} else {
  console.log("arr3 is empty");

if (arr4 && arr4.length) {
  console.log("arr4 is not empty");
} else {
  console.log("arr4 is empty");

It will print :

arr1 is not empty
arr2 is empty
arr3 is empty
arr4 is empty

Here, we are also checking if an array exists or not along with its length.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️