Check if an array has length in JavaScript & TypeScript

Written by Tom Wells on

This simple function allows you to check if an array has a length, returning a boolean (true or false). This is useful to prevent using if's like this:

const array = ['anitem']

if (array && array.length !== 0) {
  // Do something

Why use a function for this? The main benefit is adding type checking to the input, but if you're doing a lot of array length checking in your code this is a nice helper to achieve that in many places.

The function

This is the function in JavaScript:

const hasLength = (arr) => {
  const isArray = Array.isArray(array)
  return isArray && arr.length !== 0

And in TypeScript:

const hasLength = (arr: any[]): boolean => {
  return arr && arr.length !== 0

And how to use it:

// Arrays (or not)
const array = ['anitem']
const empty = []
const string = 'String'

const arrayHasLength = hasLength(array) // true
const arrayEmpty = hasLength(empty) // false
const arrayString = hasLength(string) // false, or error in TypeScript

How it works

This is obviously a very simple function, but to break it down:

  • The function accepts a single argument arr which is an array of any type (in TypeScript).
  • First, the function checks the arr is an array (when using JavaScript).
  • Then, depending on if it's an array or not, it will check the length is more than 0.
  • Finally, if both conditions are met, it will return true. Otherwise, it will return false.

Why are we checking that the arr argument is an array in JavaScript and not TypeScript? Well, TypeScript will enforce the type Array on the argument when using TS in your project. However, with JavaScript, there is no such enforcement so String data types would also work which is undesirable behaviour in this case.

Check out our JavaScript category for more JavaScript code snippets and tutorials on!