Search code examples
javascriptclassecmascript-6semanticsprivate-members

JS semantics: Why do private and public class properties seem to get reordered?


The screenshot below shows the value of new A(), but its properties were reordered.

Is there any good reason for this?

Code

class A {
  constructor() { }
  #private1 = 1;
  public1 = 11;

  #private2 = 2;
  public2 = 22;
}

new A();

Result:

enter image description here


Solution

  • Private members are not normal properties (that are keyed with strings or symbols), they do not share an ordering where they can be interspersed arbitrarily.

    In fact, private members are not enumerable at all, so you can never list them in any order. There is just no JS functionality to do that.

    The devtools (which access the object using the debugger API) apparently chose to list first the properties of the object, then the private fields of the object, in the order in which they were defined. Notice this might change at any time, you should not ascribe it any significance.