Delete a property from an object in JavaScript
Intermediate · 4 min read
Sometimes a key has to go. A bus no longer stops at Ikeja, a form field was removed, a user cleared a setting. JavaScript has an operator for this, delete, and it does exactly one thing: it removes a key from an object. That sounds simple, but people often reach for it in the wrong places, especially on arrays.
In this tutorial you will remove a stop from a manifest with delete, see why setting a value to undefined is not the same thing, and then find out what delete does to an array (it leaves a hole). Finally you will use splice, the method that really removes an array element. You need to know what objects and arrays are.
What delete does
delete obj.key removes that key and its value from the object. Afterwards, the key is not there at all: Object.keys doesn't list it and in says false.
That is different from "emptying" a key. If you write obj.key = undefined, the key is still there. It just holds undefined.
Arrays are objects too
An array stores its items under keys '0', '1', '2' and so on, plus a length. Because those positions are keys, delete works on them, but it only removes the key. It doesn't move the later items down or change the length.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
85 delete a key, and the hole it leaves in an array
fairRemove a stop from a manifest with delete. Then run delete on an array element and look at what is left. Compare with setting the value to undefined, and with splice.
Stuck? Three hints, smallest first
- 1.
delete obj.keyremoves the key; check within, not with the value. - 2. On an array,
deletedoes not move anything or changelength. - 3.
splice(index, 1)is what actually removes an element.
Step 1: delete a key
The manifest counts passengers per stop:
const manifest = { yaba: 3, ikeja: 5, lekki: 2 };
delete manifest.ikeja;
console.log(Object.keys(manifest)); // [ 'yaba', 'lekki' ]
console.log('ikeja' in manifest); // false
The key is gone. Check with in or Object.keys, not by reading the value: manifest.ikeja would give undefined whether the key was deleted or was holding undefined.
Step 2: delete doesn't tell you much
delete returns true. It returns true even when there was nothing to remove:
const manifest = { yaba: 3, lekki: 2 };
console.log(delete manifest.badagry); // true
There was never a badagry key, and delete still says true. So don't use its result to find out whether something was removed. If you care, check Object.hasOwn(manifest, 'badagry') first.
Step 3: undefined is not deleting
Here is the half-hearted version, setting the value to undefined:
const halfHearted = { yaba: 3 };
halfHearted.yaba = undefined;
console.log('yaba' in halfHearted); // true
console.log(Object.keys(halfHearted)); // [ 'yaba' ]
console.log(JSON.stringify(halfHearted)); // {}
The key survives. Object.keys still lists it. But JSON.stringify, which turns an object into text to send to a server, leaves out keys that hold undefined. So your code sees a key that the server never receives. Pick one meaning and stick to it.
Step 4: delete on an array leaves a hole
Now the wrong turn. You want to remove seat 'A2', so you try delete:
const seats = ['A1', 'A2', 'A3'];
delete seats[1];
console.log(seats.length); // 3
console.log(1 in seats); // false
console.log(seats[1]); // undefined
console.log(JSON.stringify(seats)); // ["A1",null,"A3"]
The length is still 3. Position 1 has no key at all now; this is called a hole. Reading it gives undefined, and JSON.stringify writes it as null. Some array methods, like map and forEach, skip holes, so different parts of your code may disagree about what is in the array.
Step 5: splice removes properly
splice(index, count) removes count items starting at index, and moves the later items down to close the gap:
const spliced = ['A1', 'A2', 'A3'];
spliced.splice(1, 1);
console.log(spliced); // [ 'A1', 'A3' ]
console.log(spliced.length); // 2
This is what "remove an element" usually means. splice changes the array you call it on. If you want a new array and want to leave the original alone, use filter:
const seats = ['A1', 'A2', 'A3'];
const kept = seats.filter((seat) => seat !== 'A2');
console.log(kept); // [ 'A1', 'A3' ]
console.log(seats); // [ 'A1', 'A2', 'A3' ]
The full solution
The answer panel deletes a stop from the manifest, deletes a key that was never there, sets a key to undefined, deletes an array element and looks at the hole, and then removes an element with splice. Press Run to see the output.
const manifest = { yaba: 3, ikeja: 5, lekki: 2 };
delete manifest.ikeja;
// Setting undefined is not deleting: the key stays.
const halfHearted = { yaba: 3 };
halfHearted.yaba = undefined;
// On an array, delete blanks the slot and leaves the length alone.
const seats = ['A1', 'A2', 'A3'];
delete seats[1];
// splice is the one that removes.
const spliced = ['A1', 'A2', 'A3'];
spliced.splice(1, 1);
console.log('after delete:', seats, 'length', seats.length);
console.log('as JSON:', JSON.stringify(seats));
console.log('after splice:', spliced, 'length', spliced.length);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the key is gone', Object.keys(manifest), ['yaba', 'lekki']);
test('and in agrees', 'ikeja' in manifest, false);
test('deleting a key that was never there still reports true', delete manifest.badagry, true);
test('setting undefined leaves the key behind', 'yaba' in halfHearted, true);
test('delete on an array does not change the length', seats.length, 3);
test('so there is a hole where A2 was', 1 in seats, false);
test('and JSON writes that hole as null', JSON.stringify(seats), '["A1",null,"A3"]');
test('splice removes the element properly', spliced, ['A1', 'A3']);
test('with the length to match', spliced.length, 2);
delete is about keys, and an array index is a key, which is why delete seats[1] is legal and almost never what you want. It leaves a hole: length stays 3, 1 in seats is false, and seats[1] reads as undefined without any key being there. map and forEach skip holes, JSON.stringify writes them as null, and the two behaviours together produce bugs that are miserable to trace. Use splice, or filter for a copy.
Two smaller notes. delete returns true for a key that was never there, so its return value tells you nothing about whether anything was removed — check with Object.hasOwn first if you care. And setting a key to undefined is not removal: the key survives, Object.keys still lists it, and JSON.stringify then drops it, so the two spellings differ in what reaches your server.
Common mistakes
- Using
deleteto remove an array item. It leaves a hole and keeps the length. Usespliceorfilter. - Trusting the
truethatdeletereturns. It istrueeven for a key that never existed. - Thinking
obj.key = undefinedremoves the key. The key stays,Object.keyslists it, andJSON.stringifydrops it.
Try it yourself
- Delete
lekkifrom the manifest, then add up the remaining passengers withObject.valuesandreduce. - Write
removeSeat(seats, seat)that usesindexOfandsplice, and does nothing if the seat isn't there. - Remove the
ikejakey without changing the original object:const { ikeja, ...rest } = manifest. Printrestandmanifest.