Are Javascript Object Properties assigned in order?
Standard ECMA-262 (5.1) - Section 11.1.5 - Object Initialiser
The production PropertyNameAndValueList : PropertyNameAndValueList , PropertyAssignment is evaluated as follows:
1. Let obj be the result of evaluating PropertyNameAndValueList. 2. Let propId be the result of evaluating PropertyAssignment. ... 5. Call the [[DefineOwnProperty]] internal method of obj with arguments propId.name, propId.descriptor, and false. 6. Return obj.
So yes, the order is enforced by the standard.
From the ECMAScript 6 wiki, which will define the new version of JS:
When a scope (Block, FunctionBody, Program, ModuleBody, etc.) is entered, the variables declared by all immediately contained function and class declarations are bound to their respective functions and classes. Then all class bodies are executed in textual order. A class body defines and initializes class-wide properties once when the class definition is evaluated. This includes properties on the constructor function (the “class” itself) and on its prototype property. These initializations happen in textual order.
Your source has arrived! JavaScript object properties are initialized in textual order on objects. Arrays do not (currently) always follow this rule.
Source: http://wiki.ecmascript.org/doku.php?id=harmony:classes
I will edit this post when I find the reference in ECMAScript 5, though I am certain it is there.
Edit: Found it
ECMAScript 5 does have it: http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.7 .
If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used to order the list elements in step 3 of this algorithm.
This defines the calls to DefineOwnProperty
and therefore the position of the properties in the internal table.