Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did JavaScript reorder my Object?

Tags:

javascript

For some reason this function:

function returnDoubled (numArray) {
        var newObj = {};
        for (var i = 0; i < numArray.length; i++) {
            newObj[numArray[i]] = numArray[i] * 2;
        }
        return(newObj);
    }

    console.log(returnDoubled([0, 17, 3, 1, -1, 12, 7]));

returns the following in my console:

Object {0: 0, 1: 2, 3: 6, 7: 14, 12: 24, 17: 34, -1: -2} 

Seems strange to me. Why did JavaScript choose to arrange the newObj object in this order rather than the one I specified in the array I initially passed it?

Thanks!

like image 528
i_made_that Avatar asked Nov 23 '25 23:11

i_made_that


1 Answers

The properties of objects in JavaScript do not have a defined order. The engine is free to order it in any way it likes, and different engines may behave differently in this regard. Details about this behavior can be found in this MDN article:

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype)…

So if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

If you need to have elements in a specific order, I suggest refactoring your code to use arrays instead.

like image 149
p.s.w.g Avatar answered Nov 26 '25 11:11

p.s.w.g