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?

Salman
  • 9,299
  • 6
  • 40
  • 73

1 Answers1

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229