MakeW3web

JavaScript Deleting properties

In JavaScript, you can delete properties from objects using the `delete` operator. The `delete` operator removes a property from an object, and if the property doesn't exist or cannot be deleted, it returns `false`. If the property is successfully deleted, it returns `true`.

Syntax:

delete objectName.propertyName;

Example:

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
};

console.log(person.age); // Output: 30

// Deleting the 'age' property
const result = delete person.age;
console.log(result); // Output: true

console.log(person.age); // Output: undefined

In this example, the `age` property is deleted from the `person` object. After deletion, when you try to access the `age` property, it returns `undefined`, indicating that the property no longer exists in the object.

Keep in mind that deleting a property from an object might have unintended consequences if other parts of your code rely on that property. Additionally, the `delete` operator only works on properties, not on variables or object instances.

When using the `delete` operator with bracket notation, make sure to use the property name as a string:

delete person['lastName'];

In summary, the `delete` operator allows you to remove properties from objects in JavaScript. It is essential to use this operator with caution, considering the potential consequences of deleting properties that other parts of your code might rely on.

Was this page helpful?