skip to content

In JavaScript, how does `delete obj.k` differ from `obj.k = undefined`, and what does `delete` return?

level: juniorimportance: must knowfreq 46%

answer

  1. the key itself, or only its value
  2. the in operator tells them apart
  3. true even when nothing existed
  4. non-configurable properties are the exception
  5. strict code turns false into a TypeError

basics

~20 s

delete removes the property, so the key leaves the in check and Object.keys, while assigning undefined keeps the key holding that value. delete returns true except on an own non-configurable property: false in sloppy code, a TypeError in strict.

solid answer

~50 s

`delete obj.k` removes the property itself: afterwards `'k' in obj` is `false` and `Object.keys` no longer lists it. `obj.k = undefined` keeps the property and stores the value `undefined`, so `'k' in obj` stays `true`, and a later spread such as `{ ...defaults, ...obj }` overwrites the default with `undefined`. With no inherited `k`, reading `obj.k` gives `undefined` either way, which hides the difference. `delete` returns `true` in nearly every case, even when the property never existed, so `true` does not prove anything was removed. The exception is an own non-configurable property, such as one on a frozen object: sloppy code gets `false`, while strict code, including modules and class bodies, gets a `TypeError`. `delete` only touches own properties, so an inherited value of the same name shows through afterwards. It does not free memory directly, and on an array it leaves a hole without changing `length`.

code

javascript · 11 lines
javascript
const removed = { timeout: 5 };
delete removed.timeout;

const blanked = { timeout: 5 };
blanked.timeout = undefined;

console.log("timeout" in removed, "timeout" in blanked); // false true

const defaults = { timeout: 30 };
console.log({ ...defaults, ...removed }.timeout); // 30
console.log({ ...defaults, ...blanked }.timeout); // undefined

go deeper

for a junior

State the core split: delete removes the key, assigning undefined keeps it. Show it with the in operator, since reading the property looks the same either way, and remember that delete returns true for a missing key.

for a middle

Explain the non-configurable case and the change between sloppy false and strict TypeError, why a module makes a failed delete throw, and what happens when the removed own property was shadowing an inherited one.

for a senior

Watch for undefined values overwriting defaults in spreads, delete mutating shared objects, and deletes on frozen data in module code. Prefer rest destructuring for a copy, and a Map when keys come and go at run time.

for a principal

The decision worth making is a team convention for absent versus undefined at API and persistence boundaries, because serialisers, spreads and validators treat the two differently and mixed habits produce quiet data bugs.

## What each one does to the object An object's **property** is a key plus a value. `delete` removes the whole pair. Assigning `undefined` replaces only the value and leaves the key in place. Reading the property cannot show the difference, because a missing property also reads as `undefined`, so you need a check that looks at the keys. | Check | after `delete o.k` | after `o.k = undefined` | |---|---|---| | `o.k` | `undefined` | `undefined` | | `'k' in o` | `false` | `true` | | `Object.hasOwn(o, 'k')` | `false` | `true` | | `Object.keys(o)` | `[]` | `['k']` | | `for...in` | skips it | visits it | | `JSON.stringify(o)` | `{}` | `{}` | | `{ k: 1, ...o }` | `k` stays `1` | `k` becomes `undefined` | The last two rows matter most in real code. `JSON.stringify` drops properties holding `undefined`, so a logged payload looks identical in both cases, and a bug that depends on the difference does not show up in the log. The spread row is the bug people actually hit: an options object with a key explicitly set to `undefined` overwrites a default, where a deleted key would have left the default alone. `Object.assign` copies the `undefined` in the same way. ## What `delete` returns - **`true` when the property was removed.** - **`true` when the property did not exist.** Nothing happened, and the result is still `true`, so `if (delete o.k)` tells you almost nothing. - **`true` when the name is only inherited.** The own object has nothing to remove, and the inherited property stays. - **`false` for an own non-configurable property in sloppy code.** The object is left unchanged. If you need the status without an exception in any mode, `Reflect.deleteProperty(o, 'k')` always reports a boolean for a non-configurable property. ## Strict mode and the forms that do not compile A property is **non-configurable** when its descriptor says so: everything on a frozen object, `Math.PI`, and any property defined that way with `Object.defineProperty`. **Strict mode** is on inside modules and class bodies, and in any script or function that begins with `"use strict"`. It changes the failure: 1. Deleting an own non-configurable property throws a `TypeError` instead of returning `false`. 2. `delete someVariable` is a `SyntaxError`, so the script does not load at all. In sloppy code it has no effect on a declared variable, because variables cannot be deleted. 3. `delete this.#secret` is a `SyntaxError`, because private elements can never be deleted. 4. `delete super.k` throws a `ReferenceError`, in either mode. ```javascript "use strict"; const settings = Object.freeze({ retries: 3 }); try { delete settings.retries; } catch (e) { console.log(e.name); // "TypeError" } console.log(delete settings.missing); // true ``` ## Inherited properties `delete` only affects **own** properties. Removing an own property that shadows an inherited one uncovers the inherited value, so the read changes rather than becoming `undefined`: ```javascript const child = Object.create({ color: "red" }); child.color = "blue"; delete child.color; console.log(child.color); // "red" console.log(delete child.color, child.color); // true "red" ``` ## Arrays `delete arr[1]` removes that index but leaves `length` alone, so the array gains an **empty slot**. Methods such as `forEach` and `map` skip it. To remove an element and close the gap, use `splice`. To keep the slot with no meaningful value, assign `undefined`. ## What `delete` does not do - It does not free memory directly. Memory is reclaimed once nothing references the value, so a value that another variable still points at stays alive. - It does not remove a variable, a function parameter or a `let` binding. - It does not reach up the prototype chain. ## Reading it in review - `delete obj.k` on a shared object mutates it for every holder, and `const { k, ...rest } = obj` gives a copy without the key. - A `delete` on an object that may be frozen is a possible `TypeError` in module code. - `obj.k = undefined` before a spread or an `Object.assign` is a likely overwritten default. - `if (delete obj.k)` reads as a success check, yet it passes for a key that never existed. - `delete arr[i]` in a loop is usually a mistaken `splice`, so check whether anything later relies on `length`. - A map-like object that adds and removes dynamic keys is often clearer as a `Map`, whose `delete` method reports through its result whether the key was present.

  • What does `delete` do to a property of a frozen config object when the code is in an ES module?
    It throws a `TypeError`. Freezing makes every own property non-configurable, and modules always run in strict mode, where a failed delete throws. The same line in a classic script without `"use strict"` returns `false` and leaves the object unchanged, so moving code into a module can turn a silent no-op into a crash.
  • How do you drop a key without mutating the original object?
    Use rest destructuring: `const { k, ...rest } = obj;` leaves `obj` untouched and gives `rest` a shallow copy of its own enumerable properties without `k`. That matters when the object is shared, because `delete` changes it for every holder. Lint rules may need telling that the unused `k` is deliberate.
  • How does `Reflect.deleteProperty(obj, 'k')` differ from `delete obj.k`?
    It reports the outcome as a boolean and does not throw on a non-configurable property, even in strict code. So `Reflect.deleteProperty(Object.freeze({ k: 1 }), 'k')` returns `false` where strict `delete` throws a `TypeError`. It suits code that wants to branch on failure rather than catch an exception.

Tearing a tab out of a ring binder versus keeping the tab with nothing filed behind it. You find no pages under that name either way, but only the second binder still lists the tab in its index.

  • delete frees the value's memory immediately, like delete in C++
  • Setting a property to undefined removes it from Object.keys
  • delete returning true proves that a property was actually removed
  • delete obj.k also removes an inherited k from the prototype
  • delete arr[i] shifts later elements down and shortens the array
  • delete on a frozen object always just returns false