How to Test for an Empty Array With JavaScript

Save

In Javascript, an array is an object. Like all objects, an array has properties and methods. For example, the push method is used to add a new element to an array, as in:


array.push("element");


The length property of an array stores the number of elements in the array. If the length is not greater than zero, the array is empty; otherwise it is not empty.

  • Create a function that will accept an array as a a parameter and return true if the array is empty or false if the array is not empty. For example, type:

    function arrayIsEmpty(array) {

  • Evaluate the array variable first by itself to avoid a JavaScript error that will occur if you check for an empty array on an undefined or null variable. For example, type:

    if (array &&

  • Get the length property of the array, which will be zero if the array if empty, or greater than zero if it is not. For example, type:

    if (array && array.length > 0)

    return false;

    return true;

    }

References

Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!