JavaScript Remove Property from Object

In this section, we will learn how to delete a property from an object in JavaScript.

How to Delete Object Property in JavaScript?

The `delete` operator is used to delete a property of an object.

Note that the `delete` operator only works on properties of objects and not on variables or functions.

On a successful operation, the return value of calling the `delete` operator will be true. Also, if the operation failed for whatever reason, the return value will be false.

JavaScript delete Operator Syntax:

delete objectName.propertyName;

delete objectName[“propertyName”];

Example: using delete operator in JavaScript

const obj = {
  firstName: "John",
  lastName : "Doe",
  phone: 123456789
}
const res = delete obj.phone;
console.log(res);
console.log(obj);

Output:

true

{firstName: "John", lastName: "Doe"}

In the statement:

const res = delete obj.phone;

The result of `delete obj.phone` operation is true because the `phone` is in fact a real property of the `obj` object and when invoking the `delete` operator, it actually deleted the property.

After that, when we called the `console.log(obj)` statement, the result on the browser’s console shows that the object no-longer has the `phone` property.

Note: even if we invoke the `delete` operator on a property that the target object doesn’t have it, we still get the result `true`.

Example: removing properties from objects in JavaScript

const obj = {
  firstName: "John",
  lastName : "Doe",
  
}
const res = delete obj.phone;
console.log(res);
console.log(obj);

Output:

true

{firstName: "John", lastName: "Doe"}

Here there’s no `phone` property in the `obj` object in the first place but still we got the value `true` as the returned result of the operation.

As mentioned before, we can’t use the `delete` operator to delete variables or functions. If we do so, we will get the value `false` as the result of the operation.

Example: delete variable in JavaScript

const check = "Hi there";
const res = delete check;
console.log(res);

Output:

false

Leave a Reply