Start learning free

LESSON 131 OF 675 · DICTIONARIES

Deleting a Key in TypeScript

Lesson

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