Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the elements of a javascript object initialized in a specific order?

I have a function like that:

parsers[1] = function(buf) {
    return {
        type: "init",
        name: buf.readUTF8String(),
        capacity: buf.readUInt32(),
        port: buf.readUInt16()
    };
}

Do I have any guarantee that name, capacity, and port will be initialized one after the other? Otherwise, the buffer will be read in the wrong order.

I could of course fall back on:

parsers[1] = function(buf) {
    var ret = {type: "init"};
    ret.name = buf.readUTF8String();
    ret.capacity = buf.readUInt32();
    ret.port = buf.readUInt16();

    return ret;
}
like image 999
coyotte508 Avatar asked May 08 '15 11:05

coyotte508


1 Answers

Thanks to @joews' comment, I can answer my own question.

From the link 11.1.5 Object initializer:

Syntax

ObjectLiteral :

  • { }

  • { PropertyNameAndValueList }

  • { PropertyNameAndValueList , }

PropertyNameAndValueList :

  • PropertyAssignment

  • PropertyNameAndValueList , PropertyAssignment

In short, the object constructor takes as arguments either nothing, a list of initialization values, or a list of initialization values followed by a comma.

That list of initialization value is composed by a PropertyAssignment or a list of initialization values followed by a PropertyAssignment, meaning basically a list of PropertyAssignment by recursion.

Now the question is in the last PropertyNameAndValueList , PropertyAssignment, is there a specific order in which both components are evaluated?

The production PropertyNameAndValueList : PropertyNameAndValueList , PropertyAssignment is evaluated as follows:

  1. Let obj be the result of evaluating PropertyNameAndValueList.

  2. Let propId be the result of evaluating PropertyAssignment.

  3. ...

The order will be guaranteed if 2. is sure to follow 1..

From 5.2 Algorithm conventions:

The specification often uses a numbered list to specify steps in an algorithm. These algorithms are used to precisely specify the required semantics of ECMAScript language constructs. The algorithms are not intended to imply the use of any specific implementation technique. In practice, there may be more efficient algorithms available to implement a given feature.

...

For clarity of expression, algorithm steps may be subdivided into sequential substeps.

So, the expected initialization order is element after element, from what I can gather.

like image 79
coyotte508 Avatar answered Oct 06 '22 02:10

coyotte508