[javascript] Check if an array is empty or exists

This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.

if(arrayName && arrayName.length > 0){
    //do something.
}

or thanks to tsemer's comment I added a second version

if(arrayName && arrayName.length)

Then I made a test for the second condition, using Scratchpad in Firefox:

_x000D_
_x000D_
var array1;_x000D_
var array2 = [];_x000D_
var array3 = ["one", "two", "three"];_x000D_
var array4 = null;_x000D_
_x000D_
console.log(array1);_x000D_
console.log(array2);_x000D_
console.log(array3);_x000D_
console.log(array4);_x000D_
_x000D_
if (array1 && array1.length) {_x000D_
  console.log("array1! has a value!");_x000D_
}_x000D_
_x000D_
if (array2 && array2.length) {_x000D_
  console.log("array2! has a value!");_x000D_
}_x000D_
_x000D_
if (array3 && array3.length) {_x000D_
  console.log("array3! has a value!");_x000D_
}_x000D_
_x000D_
if (array4 && array4.length) {_x000D_
  console.log("array4! has a value!");_x000D_
}
_x000D_
_x000D_
_x000D_

which also proves that if(array2 && array2.length) and if(array2 && array2.length > 0) are exactly doing the same

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?