JavaScript array is undefined | Example code

  • by

Use length property with isArray() method to check an array is undefined in JavaScript.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ⇒ do not attempt to process array
}

Or do the check for undefined first, array empty or does not exist

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Use Array some method to check array has an undefined value, it returns true if any item in the array is undefined.

JavaScript array is undefined

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    const arr = [1, 2, 3, 4, 5, 6, 7, 8, undefined, null, 0, "", -0];
    var res = arr.some(item => item === undefined);

    console.log("Array has undefined values",res)
  </script>

</body>
</html> 

Output:

JavaScript array is undefined

Filter undefined values from an array in Javascript

The filter() method creates a new array with all elements that pass the test implemented by the provided function. So, if x !== undefined, the object becomes part of the new array. If x === undefined, it is left out of the new array.

<script>
    const arr = [1, 2, 3, 4, 5, 6, 7, 8, undefined, null, 0, "", -0];
    const filter = arr.filter((x) => Boolean(x));
    
    console.log(filter)
</script>

Output: [ 1, 2, 3, 4, 5, 6, 7, 8 ]

Do comment if you have any doubt or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.