JAVASCRIPT

How do you add or remove properties from an object?

1. Adding Properties

You can add new properties to an object in multiple ways:

βœ… Dot notation

let user = {};
user.name = "John";  
user.age = 25;

console.log(user); // { name: "John", age: 25 }

βœ… Bracket notation (useful for dynamic keys or keys with spaces/special chars)

let user = {};
user["email"] = "john@example.com";
let key = "phoneNumber";
user[key] = "1234567890";

console.log(user); // { email: "john@example.com", phoneNumber: "1234567890" }

βœ… Object.assign() (merge properties into an object)

let user = { name: "John" };
Object.assign(user, { age: 25, country: "India" });

console.log(user); // { name: "John", age: 25, country: "India" }

βœ… Spread operator (...)

let user = { name: "John" };
user = { ...user, age: 25, country: "India" };

console.log(user); // { name: "John", age: 25, country: "India" }

2. Removing Properties

βœ… delete operator

let user = { name: "John", age: 25 };
delete user.age;

console.log(user); // { name: "John" }

⚠️ Note: delete removes a property from the object but does not affect the prototype.

βœ… Destructuring + rest (...)

let user = { name: "John", age: 25, country: "India" };
let { age, ...rest } = user; 

console.log(rest); // { name: "John", country: "India" }

(This doesn’t mutate the original object; instead, it creates a new one without age.)


βœ… Summary:

  • Add: obj.prop = value, obj["key"] = value, Object.assign(), spread operator.
  • Remove: delete obj.prop, or create a new object without that property using destructuring.
No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *