Check if an array is empty in javascript ES6

Javascript being a dynamic language there are multiple ways to check if an array is empty and there are new methods available when using ES6+ syntax. In this short tutorial we will check different way to check if an array or list is empty or has some values.

Article Contents

Using Optional chaining operator and length property

Javascript recently added Optional chaining operator and pretty cool and removes lot of code and increases the readability and shortens the code. So we will use this to check if our array is empty using Optional chaining operator on array’s length property.

const cards = [1, 2, 3];

if(!cards?.length) {
 // false - as cards array is not empty
}

const cars = [];

if(!cars?.length) {
 // true - ad cars array is empty
}

notice here we are not checking if given variable is array or not. this might lead to unexpected bugs in our code so in out next method we can solve this by checking if it’s of array type. then checking if it’s an empty array.

Using in-built Array.isArray util function and length property of array

Javascript Array Class has an util function called isArray which we will use to determine given value is of array type then we can use array.length property to determine if an array is empty.

const cards = [1, 2, 3];

if(Array.isArray(cards) && !cards.length) {
 // false - as cards array is not empty
}

const cars = [];

if(Array.isArray(cars) && !cars.length) {
 // true - ad cars array is empty
}

const stackfame = "is cool tech blog";

if(Array.isArray(stackfame) && !stackfame.length) {
 // false - as stackfame is not an array
}

Using Lodash _.isArray and _.isEmpty utilities

If you’re fan of lodash or use it in your code base then it provides utilities function to check if given array is empty and it leaves very less room for any unexpected bugs and breaking of production code.

// _ = lodash require or import

const cards = [1, 2, 3];

if(_.isArray(cards) && _.isEmpty(cards)) {
 // false - as cards array is not empty
}

const cars = [];

if(_.isArray(cars) && _.isEmpty(cars) {
 // true - ad cars array is empty
}

const stackfame = "is cool tech blog";

if(Array.isArray(stackfame) && _.isEmpty(stackfame)) {
 // false - as stackfame is not an array
}


So based on your preference and use case you can use above methods to check if an given array is empty in javascript, ES6 and lodash.

See also  How to run shell script file or command using Nodejs?

Leave a Comment