Review: Using JavaScript Objects

Setting object members

So far, we've only looked at retrieving (or getting) object members - you can also set (update) the value of object members by declaring the member you want to set (using dot or bracket notation), like this:

person.age = 45;
person["name"]["last"] = "Cratchit";

Try entering the above lines and then getting the members again to see how they've changed, like so:

person.age;
person["name"]["last"];

Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these in the JS console:

person["eyes"] = "hazel";
person.farewell = function () {
  console.log("Bye everybody!");
};

You can now test out your new members:

person["eyes"];
person.farewell();
// "Bye everybody!"

One useful aspect of bracket notation is that it can dynamically set both member values and member names. Let's say we wanted users to be able to store custom value types in their people data by typing the member name and value into two text inputs. We could get those values like this:

const myDataName = nameInput.value;
const myDataValue = nameValue.value;

We could then add this new member name and value to the person Object like this:

person[myDataName] = myDataValue;

To test this, try adding the following lines into your code, just below the closing curly brace of the person Object:

const myDataName = "height";
const myDataValue = "1.75m";
person[myDataName] = myDataValue;

Now try saving and refreshing, and entering the following into your text input:

person.height;

Adding a property to an object using the method above isn't possible with dot notation, which can only accept a literal member name, not a variable value pointing to a name.