0

https://jsfiddle.net/AleKS/ydsu1ema/4/

function constObj(number, name, drink) {
  this.number = number;
  this.aName = name;
  this.drink = drink;
}

var obj = new constObj(2, "Jon", "Water");

console.log(obj);
console.log(obj[Object.keys(obj)[0]]);

I am learning about constructor functions at the moment and decided to test something in jsFiddle.

I noticed the console logging obj, displays object properties in alphabetical order.

Then I used Object.keys() to access a property by index.

As per console.log, I expected index 0 to be "Jon", instead it gave me "2", which is the order in which the constructor function was declared.

In the browser console, it logs obj as declared, but when you expand the object, the same alphabetical order is displayed.

It is really confusing.

Why does that happen and if I access a property through an index, can I be always sure that the initial property position would be used ?

  • 3
    [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Andreas Jun 06 '20 at 09:25

1 Answers1

2

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

As per ES 2015 specification Objects iterate in the following order:

  1. Numeric array keys, in ascending numeric order
  2. All other non-Symbol keys, in insertion order
  3. Symbol keys, in insertion order

Order for the methods Object.keys, Object.values, Object.entries, for..in loops, JSON.stringify was not specified in ES 2015. But, as of ES2020, property order for these methods will also be guaranteed as per the above rule.

So, in your case, Object.keys will return an array in the order of ['number', 'aName', 'drink'].

The second part of your question is the order with console.log. console.log is the browser implementation, and each browser can have its own implementation.

Here is an example:

function createObj(x, y, z, a, b) {
  this[2] = x
  this.number = y
  this.aName = z
  this.drink = a
  this[1] = b
}

const obj = new createObj(1,2,3,4,5)
console.log(obj)
console.log(JSON.stringify(obj))
console.log(Object.keys(obj))
Ashish
  • 4,206
  • 16
  • 45
  • Where did you get the ES2020 from? That order has been introduced with ES2015. – Andreas Jun 06 '20 at 09:51
  • @Andreas In ES 2015 the order was defined for certain methods that iterate over properties but not `Object.keys, Object.values, Object.entries, JSON.stringify`. But, as of ES2020, property order for these methods will also be guaranteed. – Ashish Jun 06 '20 at 09:57