Explain Codes LogoExplain Codes Logo

How to check if an array is empty or exists?

javascript
array-validation
javascript-best-practices
variable-declaration
Alex KataevbyAlex Kataev·Oct 29, 2024
TLDR

The simplest method to check if an array is non-empty:

if (myArray?.length) { // Array exists and it has items }

The optional chaining (?.) prevents runtime errors when myArray is null or undefined. Checking the length property guarantees myArray contains elements.

Incorporate Array.isArray() for verifying array type:

if (Array.isArray(myArray) && myArray.length) { // It's an array, and it's not empty. Woohoo! }

This approach confirms that myArray is an array and isn't lacking elements.

Nitty-gritty array detection

When working with arrays, beware of the traps and pitfuls. Here's a deep-dive into array validation and handling all possible corner cases.

Asserting array type

if (!Array.isArray(image_array)) { console.error("Houston, we've got a problem! It's not an array!"); }

Don't trust external data

Data from external sources, e.g., server-side response or an API, should be handled with care:

// Believe nothing, trust no one. var image_array = JSON.parse(phpJsonEncodedArray || '[]');

Avoiding accidental redeclaration

Redeclaring variables should be avoided, or it may result in unexpected behaviour, you don't want unexpected "surprises", do you?

// Reuse, reduce, recycle. var image_array = image_array || [];

Managing data-loaded actions

Deal with critical actions that depend on the existence of array and its element count. For instance, loading images from an array:

if (Array.isArray(image_array) && image_array.length) { // Queue the red carpet. Our star image has arrived! loadImage(image_array[image_array.length - 1]); } else { alert("Image array is on a vacation. 🏖️"); }

Array anomalies and avoidance strategies

Be super prepped for unpredictable data, the silent destroyers of logic. Guilty as charged, arrays have some quirks:

1. Coquettish array length

Just like cats, undefined and null have no length. Be cautious!

if (yourArray && yourArray.length > 0) { // Array is alive and kicking! }

2. Variable hoisting - A magic trick gone wrong

Avoid variable hoisting (JavaScript's magic trick!) by using let or const for proper block scoping:

// Now you see it, now you don't. let yourArray = [];

3. Support the elders - Older JavaScript environments

Support developers stuck in the JavaScript Jurassic period (ES5 and below):

// Dinosaur-friendly syntax. if (yourArray && yourArray.length) { // Array exists and is not empty }

4. The grand entrance - On page load instances

A foolproof strategy for handling array-based operations at page load event:

// Lights, camera, action! window.onload = function() { if (image_array && image_array.length) { loadImage(image_array[0]); } };

Critical observations

Detect or regret

When checking arrays, stay away from ambiguous checks like if (array) that only verify existence and not emptiness:

// False positives are worse than no positives. if(yourArray !== undefined && yourArray !== null) { yourArray.length }

Variable declaration - Stick to the basics

Stick with var, let, or const to declare your variables in Javascript. The accidental global vars are no fun:

// You cannot not communicate, right? let image_array = image_array || [];

Initialization - Stay on the safe side.

Stay vigilant when initializing arrays from server-side data. Always parse or verify the data structure:

// Spoiler: Data can't be trusted. const data = Array.isArray(serverData) ? serverData : [];

To wrap it up

Always test your code with different array states (empty, filled, null, undefined). Reliability is bliss!