Clearing a Dictionary using Javascript

In JavaScript, dictionaries can be implemented using plain objects or ES6 Maps. Both approaches provide methods to clear all key-value pairs from the container.

Clearing Custom Dictionary Objects

For custom dictionary implementations using plain objects, you can create a clear() method that resets the container:

clear() {
    this.container = {}
}

Example with Custom Dictionary

class MyMap {
    constructor() {
        this.container = {};
    }
    
    put(key, value) {
        this.container[key] = value;
    }
    
    clear() {
        this.container = {};
    }
    
    display() {
        console.log(this.container);
    }
}

const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");

console.log("Before clearing:");
myMap.display();

myMap.clear();

console.log("After clearing:");
myMap.display();
Before clearing:
{ key1: 'value1', key2: 'value2' }
After clearing:
{}

Clearing ES6 Maps

ES6 Maps provide a built-in clear() method that removes all key-value pairs:

const myMap = new Map([
    ["key1", "value1"],
    ["key2", "value2"]
]);

console.log("Before clearing:");
console.log(myMap);

myMap.clear();

console.log("After clearing:");
console.log(myMap);
Before clearing:
Map(2) { 'key1' => 'value1', 'key2' => 'value2' }
After clearing:
Map(0) {}

Comparison of Methods

Method Syntax Use Case
Custom Object this.container = {} Custom dictionary implementations
ES6 Map map.clear() Built-in Map objects

Conclusion

Both custom objects and ES6 Maps support clearing operations. Use this.container = {} for custom implementations or the built-in clear() method for ES6 Maps.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements