Skip to content

Instantly share code, notes, and snippets.

@gregspurrier
Created March 19, 2014 02:34
Show Gist options
  • Save gregspurrier/9634498 to your computer and use it in GitHub Desktop.
Save gregspurrier/9634498 to your computer and use it in GitHub Desktop.
Think that properties are always enumerated in insertion order in JavaScript? Think again.
# The following is in Node, but Firefox has the same behavior
$ node --version
v0.10.26
tinker:~ greg$ node
> var x = {"z": 0, "2": 1, "0": 2, "a": 3, "-3": 4, "b": 5, "-5": 6, "1": 7}
undefined
> Object.keys(x)
[ '0',
'1',
'2',
'z',
'a',
'-3',
'b',
'-5' ]
> for (key in x) { console.log(key) }
0
1
2
z
a
-3
b
-5
undefined
@gregspurrier
Copy link
Author

This caught me by surprise today since node.js and most browsers typically maintain insertion order. Apparently when the keys are strings representing non-negative integers, they are moved to the front and put in order.

@gregspurrier
Copy link
Author

There's a lot of discussion on this topic here: https://code.google.com/p/v8/issues/detail?id=164

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment