3

Does javascript guarantees that the sequence of keys of an object gets preserved even if the new value is assigned to a key?

For example, if i have the following object

var Object = {
    keyX: value1,
    keyB: value2,
    keyZ: value3
}

If i iterate through keys using for .. in, I get the proper sequence i.e. keyX, keyB, keyZ. and if I change the value of keyB, I am still getting the same sequence in iteration.

My question is, will the sequence remains the same always, or it might change in any case?

3
  • 1
    I don't think you should rely on the order of the properties in an object. Commented Sep 12, 2012 at 12:44
  • 1
    The sequence could change at any time. Commented Sep 12, 2012 at 12:45
  • possible duplicate of Elements order in a "for (… in …)" loop Commented Sep 12, 2012 at 12:46

1 Answer 1

6

Well, it's quite clearly said in the doc (MDN):

A for...in loop iterates over the properties of an object in an arbitrary order.

And this section of documentation gives more comprehensive explanation to this:

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays.

In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.