CodeBlanks Logo Icon CodeBlanks

Adding and changing properties

JavaScript course · Beginner · Lesson 73/133

Learn to add new properties and change existing ones.

Adding properties

You can add new properties to an object later. Just assign a value using dot or bracket notation.

const user = { name: 'Alex' };
user.age = 28;
user['city'] = 'Berlin';
// user: { name: 'Alex', age: 28, city: 'Berlin' }

Even if the object is declared with const, its contents can change; const only blocks reassignment. This behavior is called mutation.

Changing properties

Changing an existing property's value uses the same assignment. You give a new value to the same key.

const user = { name: 'Alex', age: 28 };
user.age = 29;
// user.age is now 29

The only difference between adding and changing is whether the key already exists on the object. JavaScript picks the right behavior automatically.

Exercise Update the product

Change the price property of the product object to 49. Then add a discount property set to 10. Finally print product with console.log.

Show example solution
const product = { name: 'Pen', price: 25 };
product.price = 49;
product.discount = 10;
console.log(product);

Test yourself

  1. Correct way to add a property to user?

    const user = { name: 'Alex' };
    • user.age = 28;
    • user(age) = 28;
    • user->age = 28;
    • age.user = 28;
    Show answer

    user.age = 28; — Correct! Assigning with dot notation adds the property.

  2. Update the score

    const player = { name: 'Alex', score: 10 };
    player.score ____ 20;
    Show answer
    const player = { name: 'Alex', score: 10 };
    player.score = 20;
  3. Match each operation

    user.age = 28
    add age
    user.age = 29
    change age
    user.age
    read age

All lessons in Beginner