Start learning free

LESSON 131 OF 675 · DICTIONARIES

Deleting a Key in TypeScript with the delete Operator

Lesson Read the full explanation

TL ; DR:

The delete operator removes a key and its value from an object. The object has one entry fewer.


const toys: { [key: string]: number } = {"ball": 3, "doll": 2, "kite": 1};

delete toys["kite"];

console.log(Object.keys(toys).length);   // 2


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Write delete, then the object with the key in square brackets. The key and its value go away together.

The number of keys drops by 1. The key is gone, so "kite" in toys is now false.

Deleting a key that isn't there does nothing. There is no error.

Watch out: setting a value to undefined doesn't delete its key. The key stays, and Object.keys still counts it.

A const object can still lose keys. The const only stops you from giving toys a new object.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print the number of keys in animals again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · DICTIONARIES

    Deleting Dictionary Keys in TypeScript, explained

    Removing an entry

    Sometimes an entry has to go: a shop stops selling an item, or a player leaves a game. The delete operator removes a key and its value from an object together:

    const animals: { [key: string]: number } = {"cat": 4, "dog": 2, "rabbit": 1};
    console.log(Object.keys(animals).length);
    delete animals["rabbit"];
    console.log(Object.keys(animals).length, "rabbit" in animals);
    3
    2 false

    The number of keys drops by 1, and "rabbit" in animals is now false. The expression delete obj[key] also gives a result: true. That is the case even for a key that was never there, so deleting a missing key does nothing and raises no error.

    Setting to undefined is not deleting

    Assigning undefined to a key empties its value but keeps the key:

    const a2: { [key: string]: number } = {"cat": 4, "rabbit": 1};
    a2["rabbit"] = undefined;
    console.log(Object.keys(a2).length, "rabbit" in a2);
    2 true

    The object still has two keys, and Object.keys still counts "rabbit". If the goal is to remove the entry, only delete does it.

    const objects can lose keys

    The dictionary is declared with const, and the delete still works. The const only stops you from giving the name animals a new object; the object itself can change.

    Deleting several keys

    Each delete removes one entry, and the others stay. Delete the rabbit and the cat from the pet shop and one key is left; delete the dog too and the object is empty:

    delete animals["rabbit"];
    delete animals["cat"];
    console.log(animals, Object.keys(animals));
    delete animals["dog"];
    console.log(animals, Object.keys(animals).length);
    { dog: 2 } [ 'dog' ]
    {} 0

    An empty object is still a valid dictionary, and Object.keys gives an empty array for it. This is how a shop's list can shrink to nothing without any special case.

    The exercise, step by step

    A pet shop counts what it has for sale: 4 cats, 2 dogs and 1 rabbit. The last rabbit has just gone home with a family.

    1. Delete the key. Below the first console.log, write delete animals["rabbit"];.
    2. Print the number of keys again with Object.keys(animals).length. One key is gone, so it prints 2.

    The code at the bottom then checks whether the key is still there.

    const animals: { [key: string]: number } = {"cat": 4, "dog": 2, "rabbit": 1};
    console.log(Object.keys(animals).length);
    
    delete animals["rabbit"];
    console.log(Object.keys(animals).length);
    
    if ("rabbit" in animals) {
        console.log("We still have rabbits");
    } else {
        console.log("No rabbits left");
    }
    3
    2
    No rabbits left

    Reading the count of keys before and after is a handy way to see that a delete worked: 3 before, 2 after. If the two numbers are equal, the key was not there to begin with, or the spelling did not match, and the program carried on without telling you.

    Traps

    • Assigning undefined or 0 instead of deleting. The key stays, so the count stays 3 and the check says "We still have rabbits". With a value of 0 the key is also still there.
    • Deleting with the wrong spelling. Keys match exactly. delete animals["Rabbit"] removes nothing.
    • Looking for a method. Objects used this way have no remove method. The operator is delete, written before the expression.

    If you need a dictionary without some key but want to keep the original, copy it first and delete from the copy. The spread syntax { ...animals } makes a shallow copy, and delete on the copy leaves the original object alone. Deleting from the object you were given changes it for everyone who holds it.

    Key takeaways

    • delete obj[key] removes the key and its value.
    • Deleting a key that isn't there is harmless.
    • Setting a value to undefined keeps the key.
    Keep going with TypeScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free