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.
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:
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:
animalSoundsis created with three properties.- The function receives the original object as
objectand"Cow"askey. object[key]becomesobject["Cow"].delete object["Cow"]removes theCowproperty from the original object.deletereturns when the operation succeeds, so is usually .
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];
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" }
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.
Comparisons
| Operation | Result | Does the key still exist? | Mutates the original object? |
|---|---|---|---|
delete object[key] | Removes the property | No | Yes |
object[key] = undefined | Keeps a property with an undefined value | Yes | Yes |
object[key] = null | Keeps a property with a null value | Yes | Yes |
{ [key]: value, ...object } | Adds or replaces a property in a new object | Yes | No |
const { [key]: _, ...rest } = object |
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;
}
deleteremoves a property and mutates the object.deletereturns a boolean, usuallytrue.- Use
object[key]for dynamic keys. object.keyonly works for the literal property namekey.undefinedis 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;
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.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.