Is a JavaScript array order guaranteed?
Assuming a JavaScript array is posted in a form (using ajax/JQuery) is the order in the array guaranteed?
Valid question from @Quentin "Define 'posted in a form'"
$.ajax({
type: "POST",
url: url,
data: { foo: [{ name: "one" }, { name: "two" }] },
success: success,
dataType: dataType
});
Expanding on the question (because of the above), Is the array guaranteed to preserve the order on the server side?
You can always refer to the ECMAScript standard when in doubts: Array Exotic Objects
Array is a special kind of object in the language that have additional semantic on how length property is handled respect to the properties that are integers from 0 to 2^32. In javascript an array can be sparse if there are missing values in the range of 0 to the length property excluded. Various array methods take this in consideration, for example forEach ignore missing values
What is a missing value?
The language tries to make arrays act as much as possible as to normal objects: you can add any property to it and even have objects that inherit from an array.
var fruits = ["Apple", "Banana"];
fruits.preferred = "Apple";
This kind of code don't pose any problem, but if you start to write:
fruits[100] = "Strawberry";
for(let i = 0; i < fruits.length; ++i) {
...
}
100 is a property name in the range of [0, 2^32) so is an array element but at this point what fruits.length should be? It must be 101, otherwise the for loop will never get "Strawberry".
But at this point you have to accept that there is a range of element [2, 99] that were never defined: these are missing values.
Vice versa the same must be true when you modify the length property
var fruits = ["Apple", "Banana"];
fruits.length = 0;
Now a for loop will never get any element of the array: this is equivalent to emptying the fruits array.
It's also possible to increment the length, with the result of having missing values
So yes arrays are ordered as you can iterate all its elements in increasing order, but keep in mind that there can be missing values