Adding, Changing and Deleting Properties

Grade 8, page 4 of 13. A one-minute read.

Objects are flexible. You can change them any time, even if they were created with const (remember: const locks the variable, not the contents).

JavaScript
const pet = { name: "Bingo", species: "dog" };

// change a property
pet.name = "Bingo the Brave";

// add brand new properties
pet.age = 4;
pet["favorite toy"] = "old slipper";

// delete a property
delete pet.species;

console.log(pet);

It prints

{ name: 'Bingo the Brave', age: 4, 'favorite toy': 'old slipper' }

If you assign to a property that exists, it gets updated. If it doesn't exist yet, it gets created. And delete removes a property completely.

Checking if a property exists

To check whether an object has a certain property, use the in operator:

JavaScript
const pet = { name: "Bingo", age: 4 };

console.log("name" in pet);
console.log("color" in pet);

It prints

true
false

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning