JSFiddle - React, Tailwind, and code Playground
HTML
Look in the console.
JavaScript
// Rules:
// * An object's own properties come first, followed by prototype properties that
// haven't already been visited.
// * Properties with names that are "array indexes" are before others and in order
// numerically.
// * They're followed by String-named properties in creation order.
// * They're followed by Symbol-named properties in creation order (not tested here
// because we're looking at `for-in` and `Object.keys`, neither of which visits
// Symbol-named properties).
// A prototype for our target object
var p = {
// Won't be visited at all, superceded by o.foo
"foo": null,
// Will be index 6 in an `in` loop, won't be in `keys` at all (not own)
"bar": 6,
// Will be index 7 in an `in` loop, won't be in `keys` at all (not own)
"bongo": 7,
// Will be index 5 in an `in` loop (array index)
2: 5,
// Will be index 4 in an `in` loop (array index)
"1": 4
};
// Our target object
var o = Object.create(p);
// Will be index 2 visited
o.foo = 2;
// Will be index 1 visited (array index)
o[4] = 1;
// Will be index 0 visited (array index)
o["3"] = 0;
// Will be index 3 visited
o.baz = 3;
var expect = 0;
var good = true;
console.log("for-in:");
for (var name in o) {
var v = o[name];
console.log(name, v, v == expect);
good = good && v == expect;
++expect;
}
console.log("for-in: " + (good ? "All good" : "Order not respected"));
console.log("Object.keys:");
good = true;
Object.keys(o).forEach(function(name, expect) {
var v = o[name];
console.log(name, v, v == expect);
good = good && v == expect;
});
console.log("Object.keys: " + (good ? "All good" : "Order not respected"));