0
0
Javascriptprogramming~5 mins

Adding and removing properties in Javascript

Choose your learning style9 modes available
Introduction

We add or remove properties to change what information an object holds. This helps us update or clean up data easily.

When you want to add new details to an object, like adding a phone number to a contact.
When you need to remove outdated or wrong information from an object.
When building or modifying objects dynamically based on user input.
When cleaning up objects before sending data to a server.
When you want to customize objects by adding or removing features.
Syntax
Javascript
To add a property:
object.propertyName = value;

To remove a property:
delete object.propertyName;

You can add properties using dot notation or bracket notation.

Use delete keyword to remove a property from an object.

Examples
Adds a new property name with value 'Alice' to the person object.
Javascript
const person = {};
person.name = 'Alice';
Removes the brand property from the car object.
Javascript
const car = { brand: 'Toyota' };
delete car.brand;
Adds a property title using bracket notation.
Javascript
const book = {};
book['title'] = 'JavaScript Guide';
Sample Program

This program starts with a user object having username and age. It adds an email property and removes the age property. Finally, it prints the updated object.

Javascript
const user = {
  username: 'coder123',
  age: 25
};

// Add a new property
user.email = 'coder123@example.com';

// Remove the age property
delete user.age;

console.log(user);
OutputSuccess
Important Notes

Adding a property that already exists will update its value.

Removing a property that does not exist does nothing and does not cause errors.

Use bracket notation when property names have spaces or special characters.

Summary

You can add properties to objects using object.property = value.

Remove properties using delete object.property.

This helps keep objects up-to-date and clean.