Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript and/or JSON require parsers enumerate attributes in definition order?

Given an object definition:

var o = {x :1, y:2, z: 3, b: 4, a: 5, m: 6, X: 7};

At enumeration time, Chrome appears to respect the order in which the attributes are defined:

for (var i in o) { console.log(i, o[i]); }

Yields:

x 1
y 2
z 3
b 4
a 5
m 6
X 7

Does JavaScript and/or the JSON specify this level of order-preservation?

In either case, is it reliable?

like image 683
svidgen Avatar asked Jun 06 '13 20:06

svidgen


2 Answers

No, Javascript specs explicitly do not require any particular enumeration order, they are by definition unordered.

See section 12.6.4 of the ECMAScript specification:

The mechanics and order of enumerating the properties ... is not specified.

like image 154
Alnitak Avatar answered Sep 21 '22 22:09

Alnitak


There is no guarantee that the properties will appear in the order that they are defined.

Some browsers will retain the properties in the order that they are defined, others wont.

A JSON parser that parses the JSON into something other than a Javascript object could retain the order from the source, otherwise it's not possible to guarantee it.

like image 33
Guffa Avatar answered Sep 21 '22 22:09

Guffa