zerkms
zerkms

Reputation: 255005

Order of elements in React.addons.createFragment object

I'm reading the https://facebook.github.io/react/docs/create-fragment.html article and spotted that FB engineers rely on the object memory layout (the order of properties):

if (this.props.swapped) {
  children = React.addons.createFragment({
    right: this.props.rightChildren,
    left: this.props.leftChildren
  });
} else {
  children = React.addons.createFragment({
    left: this.props.leftChildren,
    right: this.props.rightChildren
  });
}

Am I missing something or they rely on unreliable and provide the fragile code?

PS: The question is asked (and I expect it to be answered) from the ES specification point of view, not some JS engine implementation perspective (which is subject to change within spec).

Upvotes: 1

Views: 847

Answers (1)

Felix Kling
Felix Kling

Reputation: 816790

(Disclaimer: I'm not speaking on behalf of Facebook, this is my own opinion)

You may have missed this note (which could be a bit more predominant):

Note also that we're relying on the JavaScript engine preserving object enumeration order here, which is not guaranteed by the spec but is implemented by all major browsers and VMs for objects with non-numeric keys.

However, the upcoming version of ECMAScript (ES6/ES2015) actually formalizes the iteration behavior (if I understand the spec correctly).

In the spec, it's said about an object's internal [[Enumerate]] method:

[[Enumerate]] must obtain the own property keys of the target object as if by calling its [[OwnPropertyKeys]] internal method.

And [[OwnPropertyKeys]] is defined as

When the [[OwnPropertyKeys]] internal method of O is called the following steps are taken:

  1. Let keys be a new empty List.
  2. For each own property key P of O that is an integer index, in ascending numeric index order
    1. Add P as the last element of keys.
  3. For each own property key P of O that is a String but is not an integer index, in property creation order
    1. Add P as the last element of keys.
  4. For each own property key P of O that is a Symbol, in property creation order
    1. Add P as the last element of keys.
  5. Return keys.

Upvotes: 7

Related Questions