DEV Community

Cover image for JavaScript Useful Array.isArray() Method
Prosen Ghosh
Prosen Ghosh

Posted on • Originally published at dev.to

JavaScript Useful Array.isArray() Method

The Javascript Array.isArray() method determines whether the passed value is an array or not.

The isArray method takes one argument as a parameter and it's return true if the passed value is an array otherwise false.

Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray(null); // false
Array.isArray(undefined); // false
Enter fullscreen mode Exit fullscreen mode

Sometimes we need to check whether the array is empty or not?
In that case we can use .length property of the array along with isArray() method.

let array = [];
if(Array.isArray(array) && array.length > 0){
    // FOUND VALUES, DO THE STAFF
}
else {
    // FOUND EMPTY ARRAY
}
Enter fullscreen mode Exit fullscreen mode

Using Node Package

We can use one of the popular package to do the task more easily.

$ npm i --save lodash
Enter fullscreen mode Exit fullscreen mode

Let's import lodash in the working file by writing the below code.

const _ = require('lodash');
Enter fullscreen mode Exit fullscreen mode

lodash package has a method call .isEmpty(). It checks if the passed value is an empty object, collection, map, or set.

Now lets use _.isEmptry() method to implement the above example.

let array = [];
if(_.isEmpty(array)){
    // FOUND VALUES, DO THE STAFF
}
else {
    // FOUND EMPTY ARRAY
}
Enter fullscreen mode Exit fullscreen mode

Official Documentation

Discussion (0)