Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm creating a UI table component that returns an array of selected indices.

Some typical return values would be

var myRetVal1 = [0];//one value selected 
var myRetVal2 = [0,1,2,3,8,11];//multiple value selected

as you can see I'm always returning an array.

I had an idea to return -1 when nothing is selected, but then I thought that might be confusing when in every other condition an array is returned.

So checking for an empty set of values would be either

//returns -1
var selectedItems = tbl.GetSelectedIndex();
if(selectedItems !== -1){
   //we have data to process


//returns []
var selectedItems = tbl.GetSelectedIndex();
if(selectedItems.length > 0){
   //we have data to process


//returns null
var selectedItems = tbl.GetSelectedIndex();
   //we have data to process

Maybe I'm making too big a deal over this, but is there a standard expectation for this type of control?

As I build other controls should they conform to a standard empty return value or should they always return a "empty" version of their expected return type?

share|improve this question
up vote 5 down vote accepted

I'd be okay with either of the latter. I don't like the first one because you're changing the actual data type returned (int rather than array).

Optimally, I'd go with the second one as it makes more semantic sense. If you're returning an array of selected items, then it makes more sense (again, semantically) to check array.length === 0 than array === null.

share|improve this answer

I would return an empty array. It bothers me when people return null collections instead of empty collections. The majority of what I would be doing with your return value will be iterating over it, mapping over it etc. and my functions will work correctly with an empty array, but will either break, or have to be modified to deal with null

The worst is when somebody writes a function that returns null for no elements, just the element for 1 element, and an array of elements for multiple elements. It can triple the size and complexity of my code just because I have to check for all the different conditions (I don't mind complex code, but I do mind unnecessarily complex code).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.