For example:
var f=function(str){
console.log(str);
return str;
};
var obj={
a:f('value A'),
b:f('value B'),
};
//some other code
does it guarantee
value A
value B
instead of
value B
value A
is printed?
Note: I'm asking the order of execution of f(), not the order of keys of Object.keys(obj).
1 Answer 1
(削除) Even though this is clearly a duplicate of Does JavaScript Guarantee Object Property Order?, I'll go ahead and answer anyway.
There is zero guarantee of order in your "unordered collection of properties". However with modern implementations of Javascript, you can expect that the properties will usually be in order as you defined them.
As long as the expected order is preferable, but not critical, it is reasonable in most cases to just assume they will be in order. But if your business logic depends on that order to be guaranteed, then you definitely need to rethink your strategy. (削除ここまで)
Okay. I see now what you are actually asking. In this particular context, the answer is "yes and no".
Your functions are being called statically as your object is being defined. So the function defining property a
will always be called before the function defining property b
.
However, console.log
is an asynchronous function, and you cannot rely on it to log value A
before it logs value B
-
2Read the comments above. The concept of an unordered collection has no bearing on the order of the evaluation of its members in its initializer.user9274775– user927477502/02/2018 02:21:43Commented Feb 2, 2018 at 2:21
-
...take this example:
var i = 0; var obj = {a:++i, b:++i, c:++i};
The key/value pairs will reliably bea:1
,b:2
, andc:3
. Enumerating the object may not visit them in that order, but the pairings will be sure. Imagine how confusing it would be if the initializing order wasn't guaranteed.user9274775– user927477502/02/2018 02:25:43Commented Feb 2, 2018 at 2:25
f
function could return an object that contains an index that is incremented on each call, thereby recording the creation order of the properties and establishing an actual, reliable order for sorting or other purposes.