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"?
Empty collection. Always. It is considered a best practice to NEVER return null when returning a collection or enumerable.
Handling null and empty arrays and objects used in JSON data is described. JSON data has the concept of null and empty arrays and objects.
If you want to split your workflow and more explicitly capture when something is not set, use null. If you would rather the program just keep doing as it does, use an empty string. The important thing is that you are consistent, pick a common return and stick with that.
Yes, JSON has the null value (which is indeed treated as a value, not as the absence of value), and the empty string, and they are different.
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:
null
seems more appropriate. []
.result[someKey]
), then use {}
.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 {}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With