Alex Rivera | Logout

How can I check JavaScript arrays for empty strings?

Asked 2010-08-11T11:34:02.977
20

I need to check if array contains at least one empty elements. If any of the one element is empty then it will return false.

Example:

var my_arr = new Array(); 
my_arr[0] = ""; 
my_arr[1] = " hi ";
my_arr[2] = "";

The 0th and 2nd array elements are "empty".

Edit
Report

1 Answer

22

You can check by looping through the array with a simple for, like this:

function NoneEmpty(arr) {
  for(var i=0; i<arr.length; i++) {
    if(arr[i] === "") return false;
  }
  return true;
}

You can give it a try here, the reason we're not using .indexOf() here is lack of support in IE, otherwise it'd be even simpler like this:

function NoneEmpty(arr) {
  return arr.indexOf("") === -1;
}

But alas, IE doesn't support this function on arrays, at least not yet.

answered 2010-08-11T11:37:45.027

Your Answer