In what situation would storing in an array different data types be useful in Javascript?

This is the case in any language that is not strongly typed. Your array members can be of different primitive and they also can be objects. In most cases you wouldn't want to use this because there is no clear structure to your array. You would rather have something like:

var data = {
    prop: 12,
    otherProp: 24.5,
    stringProp: "hello",
    boolProp: true
};

Although it is possible to store different data types in array, it is considered a poor programming style, because an Array by definition is homogeneous data structure.

How would one handle in uniform way such array:

[ 2.5 , [ 1, 2 ], ["a", "b", "c"], {min: 2, max: 5}  ]

for

  • sorting
  • serialization
  • memory utilization
  • algorithms i.e. for maximum value

It does not seem natural to have different types in array, does it?


From what I know, there's not really a rule or set of specific situations where it would be considered best practice to store values of different types all in the same array in JavaScript. This is possible just because JavaScript is dynamically typed. I don't think there's any other reason besides that.

Is it best practice to do so? IMHO, I don't think so, really. I think the reason why Java (and I mentioned Java because you said you have some background there) restricts array data types (as do many languages) is partly because it's cleaner and separates concerns. I think restricting variables/other objects in JavaScript to one data type is usually a good idea regardless of the "capability" of dynamic typing.

Edit

Jonathan Lonowski pointed out that a good application is in Function.prototype.apply, which makes sense. That's because you can pass in an array of data, all of which may have different types. That's a good situation where it would make sense that JavaScript would have dynamic typing in objects like arrays, etc.