Changing and Adding Properties

The values in an object can change. You assign a new value to a property the same way as to a variable, with =:

const pet = { name: "Bella", species: "cat", age: 2 };

pet.age = 3;
console.log(pet);
{ name: "Bella", species: "cat", age: 3 }

You can also calculate the new value from the old one, as with variables: pet.age = pet.age + 1;, or shorter pet.age += 1; or pet.age++;.

Note the difference: inside the curly braces, when you create the object, a property is written with a colon (age: 2). When you change it later, you use a dot and = (pet.age = 3;).

If you assign to a property the object doesn't have yet, JavaScript adds it at the end:

const pet = { name: "Bella", species: "cat", age: 2 };

pet.owner = "Eva";
console.log(pet);
{ name: "Bella", species: "cat", age: 2, owner: "Eva" }

That's handy, but it also means that nothing warns you about a typo here either. pet.Age = 3; doesn't change age: it adds a new property Age, and Bella stays 2 years old.

Did you notice that pet is a constant, and yet it changed? It's the same as with arrays. const means that the constant always holds the same object: you can't put a different object in it. But the properties of that object can change:

const pet = { name: "Bella", species: "cat", age: 2 };

pet.age = 3;           // fine
pet = { name: "Max" }; // TypeError: Assignment to constant variable.

Instructions

Bella has just had a birthday. At the end of the program, increase her age by 1 and print pet again. The second line should be { name: "Bella", species: "cat", age: 3 }.

Bella has found a new home. At the end of the program, add a property owner with the value "Eva" to the object and print pet once more.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/9