21

I am sending an ajax request that will search a database. If no results are found, is there a reason to choose to return null, {} or []? Is one considered "standard" or "best practice"?

6
  • What do you return if you do find results? Apr 10, 2014 at 19:33
  • I was asking the question generically on purpose, but this particular instance would be passed to the .autofill() function form autofill (jQuery plugin) by Creative Area
    – TecBrat
    Apr 10, 2014 at 19:38
  • 1
    But the answer depends on what you'd normally send back. If you normally send back an array, it wouldn't make sense to send back an empty object would it? Apr 10, 2014 at 19:44
  • I see, so this isn't a "do it this way, all the time" issue. But, in either case, null is probably the less perferred option?
    – TecBrat
    Apr 10, 2014 at 19:48
  • I think @Avish's answer addresses this pretty well. There might be a case for returning null in certain situations. If you usually return an array, and empty array is probably a good choice. But if you usually return an object, then, IMHO, null is acceptable and may be better than an empty object. If you usually return just a string or a number, then null would probably be the preferred choice. Apr 10, 2014 at 19:53

1 Answer 1

43

The differences are pretty negligible.

null is the usual way to denote "no value", but your client side code will need to explicitly check for that.

If the response actually means "here are the results, but they're empty", [] or {} might be more suitable, as long as you match the format of non-empty responses (i.e. if the client is expecting an array, don't send {}, and vice versa).

Basically:

  • If an empty result set is a special case and you want to write explicit behavior for it, null seems more appropriate.
  • If your client expects an array (e.g. it will loop through the results), then use [].
  • If your client expects a map of key-value pairs (e.g. it will loop through keys or will use result[someKey]), then use {}.
  • If your client expects a single object (i.e. it expects the result to have well-known properties and will do something like result.someProperty), then null is better than returning an empty object.

Or more clearly: If the client thinks of the result as a single value, use null. If the client thinks of it as a list, use []. If the client thinks of it as a map, use {}.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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