testing the order of properties in javascript objects

"use strict"; // Experiment - testing the order of properties in Objects let obj1 = {c: 'Fred', a: 'Hi', b: 'There'}; // non-numeric keys let obj2 = {100: 'Fred', 200: 'Hi', 300: 'There'}; // numeric-keys in ascending order let obj3 = {'100': 'Fred', '2': 'Hi', '7': 'There'}; // (quoted) numeric-keys in non-ascending order // test order of properties console.log(Object.getOwnPropertyNames(obj1)); // [ 'c', 'a', 'b' ] (insertion order) console.log(Object.getOwnPropertyNames(obj2)); // [ '100', '200', '300' ] (ascending) console.log(Object.getOwnPropertyNames(obj3)); // [ '2', '7', '100' ] (ascending) // translate objects into arrays: let arr1 = Object.keys(obj1).map(key => obj1[key]); let arr2 = Object.keys(obj2).map(key => obj2[key]); let arr3 = Object.keys(obj3).map(key => obj3[key]); console.log(arr1); // [ 'Fred', 'Hi', 'There' ] console.log(arr2); // [ 'Fred', 'Hi', 'There' ] console.log(arr3); // [ 'Hi', 'There', 'Fred' ] // for ... in loops for (let item in obj1) { console.log(item); } for (let item in obj2) { console.log(item); } for (let item in obj3) { console.log(item); } // Tested on Node, Edge, Chrome, IE11, Firefox // Not tested: Safari // verdict: there is no guarantee in the ECMA spec (ecma-262) about the order of object properties. // However, in Practice: // Firefox, Node, Edge, Chrome, IE11: // properties with non-numeric keys are iterated in the order they were inserted, // properties with numeric keys are sorted in ascending order (this includes "stringified" numbers eg "100" or '100') // // more info here: https://bugs.chromium.org/p/v8/issues/detail?id=164
When you insert properties into an object, and then iterate over that object (eg with a for .. in loop). In what order are the properties retrieved ? This experiment aims to find out.

Verdict:
======

There is no guarantee in the ECMA spec (ecma-262) about the order of object properties.
However, in Practice:
Firefox, Node, Edge, Chrome, IE11:
Properties with non-numeric keys are iterated in the order they were inserted,
Properties with numeric keys are sorted in ascending order (this includes "stringified" numbers eg "100" or '100')

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.