×

javascript · level 2 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Change or add a key with a dot, or look one up with brackets.

Put a new value in with a dot and =: pet.age = 4; overwrites the age. Use a key the object has never had, and it is added: pet.vet = "Dr Khan";. A const object can still change inside, because const only stops the variable holding a different object.

Sometimes the key's name is in a variable, like field holding "name". Then use : pet[field] looks up the key held inside field. pet.field would look for a key really called field.

Ask for a key that is not there and you get undefined.

const pet = { name: "Rex", age: 3 };
pet.age = 4;
pet.vet = "Dr Khan";
const field = "name";
console.log(pet[field], pet.field);
console.log(pet);

Brackets take any string, so pet["age"] and pet.age mean the same thing.