javascriptobjectsquare-bracket

What do square brackets mean after a variable name in JavaScript?


function(property, res, err, result){
    var json = {};
    json[property] = result;
    res.json(json);
};

Okay, this is a function that will take the above parameters. When invoked it creates an Object called json, my question is about the next line I don’t understand it at all, is the object then the list of properties? Please enlighten me.


Solution

  • There are 2 ways to set the properties on objects. Most times people use dot notation like this:

    json.property = result;
    

    But if the property name is a string (which is what will be passed in as the property argument), the way the object property is set is like this:

    json[property] = result
    

    For example if someone puts these arguments into the function ("name", blah, blah, "Sam"), what is actually happening in the line in question is:

    json["name"] = "Sam"
    

    Which is equivalent to:

    json.name = "Sam"
    

    And results in an object named json that looks like this:

    {
      name: "Sam"
    }