Wissem
Wissem

Reputation: 1725

JavaScript function returning multiple variable: Array vs Object. What's the best practice?

Should we use an Array or an Object for getting multiple variables from JavaScript functions? Does is it even matter? What's considered the best practice for doing this?

Upvotes: 1

Views: 707

Answers (5)

jbabey
jbabey

Reputation: 46647

Here's the rule of thumb:

If you need string indexes, or numeric indexes that aren't 0...N, use an object.

If you don't, or if order is important, use an array.

Upvotes: 0

Antimony
Antimony

Reputation: 39451

If you're willing to use Coffescript, you can just return a tuple.

weatherReport = (location) ->
  # Make an Ajax request to fetch the weather...
  [location, 72, "Mostly Sunny"]

[city, temp, forecast] = weatherReport "Berkeley, CA"

Upvotes: 0

Thomas Johan Eggum
Thomas Johan Eggum

Reputation: 915

If order counts use an Array, an object does not know the sequence of its atributes. Please take a look at this question, it may answer some of your questions: Objects vs arrays in Javascript for key/value pairs

Upvotes: 1

jfriend00
jfriend00

Reputation: 707366

It totally depends upon what type of data you're returning. If you're returning a variable list of things that are all of the same type and thus don't need to be separately identified or if order counts, then you should put them in an array and return the array.

If you're returning N things that are not all the same things, then you should put them in an object with property names and return the object. While you could also return these in an array and just have an implied rule that the first item in the array is the "x" coordinate and the second item in the array is the "y" coordinate and then third item is the "width" and so on, your code is a lot more self documenting if you use the object with named properties where the code actually identifies which is which. In the long run, I think this is more maintainable (especially by people that didn't write the original code).

Upvotes: 3

Mårten Wikström
Mårten Wikström

Reputation: 11344

Use an object so that you can name your return values.

Upvotes: 2

Related Questions