0

I'm trying to figure out what a piece of coding in FreeCodeCamp is doing, more specifically the method Object.keys(obj). The examples that are given documentation pertain to objects whose key id's are numbers. What I noticed is that the method orders the id's from smallest to largest, is that correct? If so what happens when the key id's are strings? Do they get ordered and if so how?

 // array like object
    var obj = { 0: 'a', 1: 'b', 2: 'c' };
    console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']

I'm trying to understand exactly what happens every step of the way with this code:

json.forEach(function(val) {
  var keys = Object.keys(val);
  html += "<div class = 'cat'>";
  keys.forEach(function(key) {
    html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
  });
  html += "</div><br>";
});
manuel
  • 105
  • 10

1 Answers1

2

MDN says:

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop

and

MDN says:

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


The order is arbitrary. It is implementation specific. The JavaScript language doesn't care.

The particular (and unspecified) JS engine you are using might have some rules it applies, but you shouldn't depend on them.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • This post has additional notes and links to the spec to back up this answer. http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – JonSG Oct 03 '16 at 14:43
  • Alright but how do you explain: // array like object with random key ordering var an_obj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(Object.keys(an_obj)); // console: ['2', '7', '100'] Why does it not output [100, 2, 7] – manuel Oct 03 '16 at 14:50
  • @manuel — I refer you back to the last paragraph of the answer. – Quentin Oct 03 '16 at 14:52
  • okay I just thought that since is came from the mozzilla documentation it would not be prone to a different js engine.Thank You very much Quentin, the help is much appreciated. – manuel Oct 03 '16 at 14:54
  • Mozilla document the language. They are pretty good at marking non-standard features. – Quentin Oct 03 '16 at 14:54