Question

Remove a Key from a JavaScript Object with delete

Question

Given the following JavaScript object, how can I create a function that removes a property by its key? For example, calling removeFromObjectByKey("Cow") should remove the Cow property.

const thisIsObject = {
  Cow: "Moo",
  Cat: "Meow",
  Dog: "Bark"
};

Short Answer

You will learn how to remove properties from JavaScript objects with the delete operator, how mutation affects the original object, and how to create a new object without a property when immutability is needed.

Concept

JavaScript objects store values under property keys. In this object, Cow, Cat, and Dog are keys, while "Moo", "Meow", and "Bark" are their values.

To remove a property from an object, use JavaScript's delete operator:

delete object[key];

delete removes the property itself, not merely its value. After deletion, reading that property produces undefined, and the key no longer appears in Object.keys().

This matters because objects are commonly used as records, configuration containers, caches, lookup tables, and API payloads. Removing a field is different from setting it to an empty value: a removed property is absent, while a property set to undefined still exists.

Mental Model

Think of an object as a labelled filing cabinet:

  • Each key is a label on a drawer.
  • Each value is what is inside that drawer.
  • delete object[key] removes the whole labelled drawer.

For example, delete animalSounds.Cow removes the Cow drawer completely. Setting animalSounds.Cow = undefined leaves the Cow drawer in place, but makes its contents undefined.

Take Quiz

Syntax and Examples

Use bracket notation when the key is stored in a variable or passed into a function.

const animalSounds = {
  Cow: "Moo",
  Cat: "Meow",
  Dog: "Bark"
};

function removeFromObjectByKey(object, key) {
  delete object[key];
}

removeFromObjectByKey(animalSounds, "Cow");

console.log(animalSounds);
// { Cat: "Meow", Dog: "Bark" }

object[key] means “look up the property whose name is stored in key.” In the call above, key is "Cow", so JavaScript runs:

delete animalSounds["Cow"];

You can also use dot notation when the property name is known in advance:

delete animalSounds.Cat;

However, this does not work for a variable key:

const key = "Dog";
delete animalSounds.key; // Tries to delete a property literally named "key"

Step by Step Execution

Consider this code:

const animalSounds = {
  Cow: "Moo",
  Cat: "Meow",
  Dog: "Bark"
};

function removeFromObjectByKey(object, key) {
  return delete object[key];
}

const wasRemoved = removeFromObjectByKey(animalSounds, "Cow");

console.log(wasRemoved);
console.log(animalSounds);

Step by step:

  1. animalSounds is created with three properties.
  2. The function receives the original object as object and "Cow" as key.
  3. object[key] becomes object["Cow"].
  4. delete object["Cow"] removes the Cow property from the original object.
  5. delete returns true when the operation succeeds, so wasRemoved is usually true.
  6. animalSounds now contains only Cat and Dog.

Output:

true
{ Cat: "Meow", Dog: "Bark" }

Deleting a key that is not present usually also returns true and leaves the object unchanged.

Real World Use Cases

Common uses for removing object properties include:

  • Removing sensitive data before returning an API response

    delete user.passwordHash;
    delete user.resetToken;
    
  • Clearing an item from an in-memory cache

    delete cache[productId];
    
  • Removing a filter from search settings

    delete filters.category;
    
  • Cleaning optional fields before sending a request

    if (!payload.middleName) {
      delete payload.middleName;
    }
    
  • Managing a lookup object, such as selected items indexed by ID

    delete selectedById[itemId];
    
Take Quiz

Real Codebase Usage

In application code, choose whether changing the existing object is appropriate.

Mutating an existing object

Use delete when the object is local, temporary, or intentionally shared and changing it is expected.

function removeCacheEntry(cache, id) {
  delete cache[id];
}

Returning a new object without the key

In state-management code, it is often safer to avoid mutation. Object rest syntax creates a new object while excluding one property.

function withoutKey(object, keyToRemove) {
  const { [keyToRemove]: removedValue, ...remaining } = object;
  return remaining;
}

const animalSounds = {
  Cow: "Moo",
  Cat: "Meow",
  Dog: "Bark"
};

const updatedSounds = withoutKey(animalSounds, "Cow");

console.log(updatedSounds);
// { Cat: "Meow", Dog: "Bark" }

console.log(animalSounds);
// { Cow: "Moo", Cat: "Meow", Dog: "Bark" }

This immutable pattern is common when updating UI state because code can compare the old and new object references reliably.

Validate inputs when needed

If a function accepts unknown input, verify that it received an object first:

function removeKey(object, key) {
  if (object === null || typeof object !== "object") {
    throw new TypeError("Expected an object");
  }

  delete object[key];
}

Common Mistakes

Using dot notation with a variable

This tries to remove a literal property called key.

const key = "Cow";
delete animalSounds.key; // Wrong for variable keys

Use brackets instead:

delete animalSounds[key];

Setting the value to undefined

This does not remove the property.

animalSounds.Cow = undefined;

console.log("Cow" in animalSounds); // true
console.log(Object.keys(animalSounds)); // Includes "Cow"

Use delete animalSounds.Cow when the property should be absent.

Expecting delete to return the removed value

delete returns a boolean, not the value that was removed.

const removed = delete animalSounds.Cow;
console.log(removed); // true, not "Moo"

Save the value first if you need it:

const sound = animalSounds.Cow;
delete animalSounds.Cow;

Accidentally mutating shared data

Objects are passed by reference. If another variable refers to the same object, it will observe the deletion.

const original = { Cow: "Moo" };
const alias = original;

delete alias.Cow;
console.log(original); // {}

Create a new object with rest syntax if the original must remain unchanged.

Trying to delete from a const object variable

const prevents reassigning the variable; it does not make the object immutable.

const animalSounds = { Cow: "Moo" };
delete animalSounds.Cow; // Valid

// animalSounds = {}; // Error: reassignment is not allowed

Comparisons

OperationResultDoes the key still exist?Mutates the original object?
delete object[key]Removes the propertyNoYes
object[key] = undefinedKeeps a property with an undefined valueYesYes
object[key] = nullKeeps a property with a null valueYesYes
{ [key]: value, ...object }Adds or replaces a property in a new objectYesNo
const { [key]: _, ...rest } = objectProduces a new object without the keyNo, in the new objectNo

Use delete when changing the current object is intended. Use object rest syntax when you need an updated copy and must preserve the original.

Take Quiz

Cheat Sheet

// Remove a known property
delete object.name;

// Remove a property whose key is in a variable
const key = "name";
delete object[key];

// Function that mutates the input object
function removeKey(object, key) {
  delete object[key];
}

// Return a new object without a key
function withoutKey(object, key) {
  const { [key]: removed, ...remaining } = object;
  return remaining;
}
  • delete removes a property and mutates the object.
  • delete returns a boolean, usually true.
  • Use object[key] for dynamic keys.
  • object.key only works for the literal property name key.
  • undefined is a value; it does not remove a property.
  • Object.hasOwn(object, key) checks whether an object has its own property before deletion when that check is useful.

FAQ

How do I delete a property from a JavaScript object?

Use delete object.property for a known property name or delete object[key] when the key is stored in a variable.

Does delete remove the key or just its value?

It removes the property itself: both the key and its associated value are removed from that object.

Does delete object[key] change the original object?

Yes. It mutates the object passed to it. Return a copied object with rest syntax if mutation is not wanted.

Is delete the same as assigning undefined?

No. Assigning undefined keeps the key. delete removes the key entirely.

Can I delete a property from an object declared with const?

Yes. const prevents reassignment of the variable, but object properties can still be changed or removed unless the object has been made immutable.

How can I remove a key without mutating an object?

Use computed property destructuring:

const { [keyToRemove]: removed, ...newObject } = originalObject;

newObject contains every property except keyToRemove.

What happens if I delete a key that does not exist?

Normally nothing changes, and the delete expression returns true.

Take Quiz

Mini Project

Description

Build a small preference manager for an application. Preferences are stored in an object, and a user can reset one preference by removing its key. The project demonstrates dynamic property access, delete, and an immutable alternative for state updates.

Goal

Create functions that remove a preference by name, both by mutating an object and by returning an updated copy.

Requirements

Use an object containing at least three preferences. Create a function that removes a preference by a dynamic key using delete. Show that the mutable function changes the original preferences object. Create a second function that returns a new preferences object without the requested key. Log the results of both approaches.

Take Quiz

Keep learning

Related questions

View more