1
let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};

let myF = obj => { for(let prop in obj){
if(typeof obj[prop] == "number" ){
obj[prop] *= 2}

}  

}

myF(menu);
console.log(menu);

I have created a function that multiplies all numeric properties. While I was working in online code editor jsfiddle, the properties of menu object were surprisingly sorted alphabetically:

{
  height: 600,
  title: "My menu",
  width: 400
}

I just wonder why online code editors behave like that. Also, in my opinion, this feature can easily misdirect while working with massive code lines, so is it a bad habit to code in such places?

  • Are you saying that they were reordered in the source code? You probably pressed the "Format code" button, and the chosen formatter has a setting to sort simple objects alphabetically. – Bergi Jul 26 '20 at 10:38
  • No, it doesn't affect the source code. When I run console.log(menu) to see output at the end, it just reorders properties of the object in the console of jsfiddle and codepen. I do not interact any of these format buttons. @Bergi – Özgür Coşkuner Jul 26 '20 at 11:23
  • Ah ok. Well, objects are not an ordered data structure, it shouldn't matter in what order they are printed. Use a `Map` instead if you want to rely on iteration order. – Bergi Jul 26 '20 at 13:08

1 Answers1

0

A for...in loop iterates over the properties of an object in an arbitrary order.Your code is not affected by the order.

Asutosh
  • 1,775
  • 2
  • 15
  • 22
  • 1
    "*A for...in loop iterates over the properties of an object in an arbitrary order*"—As of ES2020, that is [not true anymore](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties). – str Jul 26 '20 at 09:22
  • But, when I run this code in browser's console, object properties are sorted in original order. – Özgür Coşkuner Jul 26 '20 at 09:32
  • @ÖzgürCoşkuner it depends which version of ES, fiddle uses and which one being used by your browser. – Asutosh Jul 26 '20 at 09:34
  • @str The order might be deterministic now for consistency between engines, but that doesn't mean that objects are supposed to be used as an ordered structure now. – Bergi Jul 26 '20 at 13:10
  • @Bergi I agree, I was not meaning to imply that. – str Jul 26 '20 at 13:28