[Solved!] Quiz Time, JavaScript Through the Ages Edition

Thanks to Jason for giving the last quiz a go before Todd Sprinkel swooped in with the correct answer:

Object.keys() wasn't a guaranteed predictable order until ES6 I think, so on an older browser (like any version of IE) your order may not be the same in the fruitNames array as it is in your fruitBasket object. Using indexOf of course the order is important, so you might get the wrong result?

Todd hit the exact target. See, I chose my language carefully in the original post:

Your website supports any browser that has a native Object.keys function, and you’re writing some basic JS.

I said only that the browser had to support Object.keys (i.e. feature detection) rather than referring to exact browsers and/or browser versions.

Object.keys is in IE 9, and could also be supported in any number of obscure/homemade browsers. (Never said it had to be a brand name, after all!)

But what constitutes a “standards-compliant implementation of Object.keys” has changed significantly over time. So the behavior depends on

(a) what the ECMAScript spec looked like at the time the software was written

and also

(b) which ES version the developer decided to conform to, which is always behind the very latest

The spec is not exactly easy reading, but you can see that in ES5 (2011) the order of keys was still unspecified, and it wasn’t until ES6 (2015) that the ordering algorithm was specified. That now-official order — if you’re not aware — is that numeric String keys come first, followed by stringy String keys, followed by Symbols.

Since you don’t know how Object.keys is going to order its results, you have to treat them as if they might be in different order on every invocation, crazy as that seems. The A Wrong Way code wrongly expects 2 results from Object.keysto have the same order. In contrast, A Right Way only calls Object.keys once, so it doesn’t matter what the order was, it could be random or alphabetical or anything.

JSON is still unordered

So you don’t get the wrong idea: JSON object keys are still unordered, even now. Because JSON is not JavaScript, it’s a universal stringification method whose look-and-feel comes from JavaScript.

In later post, I’m going to get into this in a big way w/r/t Velocity objects.