how to check an array is empty or not in javascript


To check the array is empty or not, we need to follow these steps

  1. Check whether the array is undefined or not.

    • first we need to check for the array is defined or not i.e initialized or not as follows
    •  
      var arr = [];
      if(arr != undefined)

  2. Check whether the array is null or not.

    • if we are getting data from remote source we need to check for null as follows

    • var arr = [];
      if(arr != undefined && arr != null)

  3. Check whether the type is object or not.

    • to avoid type related problems we need to check for the type as follows

    • var arr = [];
      if(arr != undefined && arr != null && typeof(arr) == typeof([]))

  4. Check whether the length of the array using length property.

    • If we want to check whether the array is having data or not we can use length property on array

    • var arr = [];
      if (arr != undefined && arr != null && typeof (arr) == typeof ([]) && arr.length > 0)

Full Example

var arr = [];
if (arr != undefined && arr != null && typeof (arr) == typeof ([]) && arr.length > 0) {
    //TODO: if the array has something in it
}
else {
    //TOTO: if the array is empty or null or undefined
}

 

Happy coding..!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s