• When you have an object with (named) properties - var o = {n:3,s:"str"}, think of the square brackets

    • either as

      • short form of getter and setter methods to access properties n and s with the property name as string "n" and "s":

        o.getN = function() { return this.n; };
        o.setN = function(n) { this.n = n; };
        
      • which you use as, for examples

        o.getN();  o.setS("me");
        
    • that equals to

      • o["n"]; o["s"]="me";

    • or

      • (pseudo) array accessors with arbitrary index, where index is property name as string

    • or

      • map or directory (object) accessors with key, where key is property name as string

    After all, it is just syntax, and the interpreter knows what kind 'thing' it is that is in front of the square brackets:

    • either

      • a real Array object (w/ consecutive, numerically indexed series of - usually - adjacent storage slots - then the value in the brackets has to be a number

    • or

      • a real Object (w/ arbitrary 'indexed'/ named properties) - then the value in the brackets has to be a property name as string (see also JSON - JavaScript Object Notation - an object declaration in string form: oAsJSONString = '{"n":3,"s":"str"}' - see JSON.stringify(o)/.parse(oAsJsonString) - PS: also supporting arrays... )

    Even though the Array is also an object... it is fundamentally different intrinsic to the implementation and behaves as such differently, even though it has similar looks and analogue functionality - as JSON shows.

    On the other hand, you can think reverse:

    o.n is the short form of o["n"]...

    After all it is just a notation by convention and pure syntax - sugar or salt, what ever you like - that spices up the code... (hence it's name code, coding, codified meaning).

    There is more of the CS Formal Languages theory/philosophy around this... like What are the real, realm specific differences between {n:3,s:"str"} and [3,"str"] and '{"n":3,"s":"str"}' ? ... may be at another post's time...

About

Avatar for allObjects @allObjects started