JavaScript delete Operator Tutorial with Examples

The delete operator in JavaScript is used to remove properties from objects. It can be useful when you want to clean up or remove unwanted properties from an object, but it is not used for deleting variables or array elements in the traditional sense.

In this tutorial, you’ll learn:

What is the delete operator?
Using delete with objects
Using delete with arrays
What delete does NOT do
Checking if a property has been deleted
Practical examples of the delete operator

1. What is the delete Operator?

The delete operator is used to remove a property from an object. It returns true if the property was successfully deleted, or false if the operation failed (e.g., if the property was non-configurable).

Syntax:

delete object.property;

or

delete object['property'];

object: The object from which the property is to be deleted.
property: The name of the property to delete.

2. Using delete with Objects

In JavaScript, objects are collections of key-value pairs. The delete operator allows you to remove a specific key (property) from an object.

Example 1: Deleting a Property from an Object

const person = {
    name: "Alice",
    age: 25,
    city: "Paris"
};

// Deleting the 'age' property
delete person.age;

console.log(person);
// Output: { name: 'Alice', city: 'Paris' }

In this example:

The age property is deleted from the person object.
After the deletion, the object no longer contains the age property.

Example 2: Deleting a Property Using Bracket Notation

You can also use bracket notation to delete properties.

const car = {
    make: "Toyota",
    model: "Corolla",
    year: 2018
};

// Deleting the 'model' property
delete car['model'];

console.log(car);
// Output: { make: 'Toyota', year: 2018 }

Both dot notation and bracket notation work in the same way, and the choice between them depends on your coding style and whether the property name is dynamically generated.

Example 3: Deleting a Non-Existent Property

If you try to delete a property that doesn’t exist, the delete operator returns true but makes no changes to the object.

const book = {
    title: "1984",
    author: "George Orwell"
};

// Deleting a non-existent property
const result = delete book.publisher;

console.log(result);  // Output: true
console.log(book);    // Output: { title: '1984', author: 'George Orwell' }

In this example:

The publisher property doesn’t exist in the book object.
The delete operation returns true but doesn’t change the object.

3. Using delete with Arrays

While you can technically use the delete operator on arrays to remove elements, it is not recommended because it leaves a hole in the array (an undefined element). The length of the array is not affected by delete.

Example 4: Using delete on Array Elements

const fruits = ["apple", "banana", "orange"];

// Deleting the second element ('banana')
delete fruits[1];

console.log(fruits);  // Output: [ 'apple', <1 empty item>, 'orange' ]
console.log(fruits.length);  // Output: 3

In this example:

The delete operator removes the element at index 1 (banana), but it leaves an empty slot.
The length of the array remains 3, and the empty slot is shown as <1 empty item>.

Recommended: Using splice() to Remove Array Elements

If you want to remove an element from an array without leaving an empty slot, you should use the splice() method.

const fruits = ["apple", "banana", "orange"];

// Removing the second element using splice
fruits.splice(1, 1);  // Removes 1 element at index 1

console.log(fruits);  // Output: [ 'apple', 'orange' ]
console.log(fruits.length);  // Output: 2
splice() correctly removes the element and adjusts the length of the array.

4. What delete Does NOT Do

The delete operator has a few limitations that are important to understand.

4.1. delete Does Not Affect Variables

You cannot use the delete operator to remove a variable that was declared with var, let, or const. Attempting to do so will return false and leave the variable intact.

var x = 10;
delete x;  // Fails silently (does nothing)

console.log(x);  // Output: 10

In this example:

The delete operator cannot remove the variable x.
Variables declared with var, let, or const are not deletable.

4.2. delete Does Not Remove Array Elements Properly

As shown earlier, delete removes the element but leaves an undefined slot in the array. The splice() method is better suited for removing elements from arrays.

5. Checking if a Property Has Been Deleted

You can use the in operator or hasOwnProperty() method to check whether a property exists in an object after it has been deleted.

Example 5: Checking Property Existence with in

const person = {
    name: "Alice",
    age: 25
};

// Deleting the 'age' property
delete person.age;

console.log('age' in person);  // Output: false
console.log('name' in person);  // Output: true

In this example:

The in operator checks whether a property exists in the object.
After deleting the age property, the in operator returns false.

Example 6: Checking Property Existence with hasOwnProperty()

The hasOwnProperty() method also checks if a property exists on an object and whether it is a direct property (not inherited).

const car = {
    make: "Toyota",
    model: "Corolla"
};

// Deleting the 'model' property
delete car.model;

console.log(car.hasOwnProperty('model'));  // Output: false
console.log(car.hasOwnProperty('make'));   // Output: true

In this example, hasOwnProperty() confirms whether the properties are still present after deletion.

6. Practical Examples of the delete Operator

Example 7: Cleaning Up Objects Dynamically

You can use the delete operator in loops to remove multiple properties from an object.

const user = {
    name: "Alice",
    age: 25,
    city: "Paris",
    email: "alice@example.com"
};

const fieldsToRemove = ["age", "city"];

// Deleting multiple properties dynamically
fieldsToRemove.forEach((field) => delete user[field]);

console.log(user);  // Output: { name: 'Alice', email: 'alice@example.com' }

In this example:

A loop iterates over the fieldsToRemove array and deletes the corresponding properties from the user object.

Example 8: Conditionally Deleting Object Properties

You can delete properties from an object conditionally, based on certain criteria.

const product = {
    name: "Laptop",
    price: 1200,
    discount: 10,
    stock: 0
};

// Conditionally delete 'discount' if stock is 0
if (product.stock === 0) {
    delete product.discount;
}

console.log(product);  // Output: { name: 'Laptop', price: 1200, stock: 0 }

In this example, the discount property is deleted if the stock is 0.

Conclusion

The delete operator in JavaScript is a useful tool for removing properties from objects, but it comes with limitations when dealing with variables and arrays. Here's a summary of what you’ve learned:

The delete operator is used to remove properties from objects.
It returns true if the deletion is successful, and false otherwise.
When used on arrays, delete leaves empty slots, so splice() is a better option for removing elements.
You cannot use delete to remove variables declared with var, let, or const.
Use the in operator or hasOwnProperty() method to check if a property has been deleted.

With these examples, you are now well-equipped to use the delete operator effectively in your JavaScript code!

Related posts

JavaScript typeof Operator Tutorial with Examples

JavaScript Grouping Operator Tutorial with Examples

JavaScript Comma Operator Tutorial with Examples