2

How javascript object is sorting itself in ascending order of keys?

I noticed it for the first time.

/* It does maintain a order. The order in which you inserts the value. And if it does not maintain any orders, please show me example, that will be really helpful to understand me the concepts.

Thanks in advance.
*/

var a = {"13" : "1", "15" : "2", "14" : "3", "12" : "4"};

console.log(JSON.stringify(a)); /* This is nothing to do with for loop */ 

for(let i in a) {
	console.log(i + " = " + a[i]);
}
/* But the keys other than numbers are not sorting. */
var b = {"c" : "1", "a" : "2", "b" : "3", "d" : "4"};

for(let i in b) {
	console.log(i + " = " + b[i]);
}

First object is sorted by itself. I am creating keys as string for both the objects. But the second object is not sorting.

0

2 Answers 2

3

This behavior is now part of the JavaScript standard:

  1. For each own property key P of O that is an integer index, in ascending numeric index order

    a. Add P as the last element of keys.

  2. For each own property key P of O that is a String but is not an integer index, in property creation order

    a. Add P as the last element of keys.

Here is a detailed explanation:

http://2ality.com/2015/10/property-traversal-order-es6.html

In short, the rationale is as follows:

  • Logically, the order should not be important and programmers should not depend on it.
  • However most browsers produce a deterministic order and programs do, in fact, depend on this order. If the browser change their order, some programs start to "break".
  • Here are two different approaches to resolve this problem:
    • Acknowledge in the standard that the order is deterministic --- so that programmers can rightly depend on it.
    • Force programmers to understand this issue by producing a different order at each run of the program.
  • Historically, the second solution was easier to implement (at least, this is what I remember from working with Perl). But today, the first option is easier.
  • So the standardizing body decided to make the deterministic order part of the standard.
Sign up to request clarification or add additional context in comments.

Comments

0

I found this answer that relates to the question you're asking.

Quote:

It's the way v8 handles associative arrays. A known issue Issue 164 but it follows the spec so is marked 'working as intended'. There isn't a required order for looping through associative arrays.

A simple workaround is to precede number values with letters e.g: 'size_7':['9149','9139'] etc.

The standard will change in the next ECMAScript spec forcing [chrome] developers to change this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.