Creating Dictionary using Javascript

In JavaScript, dictionaries can be created using objects, the ES6 Map class, or custom implementations. Each approach offers different features and use cases.

Using Objects as Dictionaries

The simplest way to create a dictionary is using plain JavaScript objects:

// Creating a dictionary using object literal
const dict = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
};

console.log(dict["key1"]);
console.log(dict.key2);
value1
value2

Using ES6 Map Class

The Map class provides a more robust dictionary implementation with additional methods:

// Creating empty map
const map1 = new Map();
map1.set("key1", "value1");
map1.set("key2", "value2");

// Creating map with initial values
const map2 = new Map([
    ["key1", "value1"],
    ["key2", "value2"]
]);

console.log(map1.get("key1"));
console.log(map2.get("key2"));
value1
value2

Custom Dictionary Class

Creating a custom MyMap class provides control over functionality:

class MyMap {
    constructor() {
        this.container = {};
    }
    
    set(key, value) {
        this.container[key] = value;
    }
    
    get(key) {
        return this.container[key];
    }
    
    hasKey(key) {
        return key in this.container;
    }
    
    display() {
        console.log(this.container);
    }
}

const myDict = new MyMap();
myDict.set("name", "John");
myDict.set("age", 30);
myDict.display();
{ name: 'John', age: 30 }

Checking if a Key Exists

Different methods to check key existence:

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

console.log(myMap.has("key1"));
console.log(myMap.has("key3"));

// Using 'in' operator with objects
const obj = {"key1": "value1", "key2": "value2"};
console.log("key1" in obj);
console.log("key3" in obj);
true
false
true
false

Comparison

Method Key Types Built-in Methods Best For
Object Strings only Limited Simple key-value storage
Map Any type Many (set, get, has, delete) Complex dictionaries
Custom Class Depends on implementation Custom methods Specific requirements

Conclusion

Use plain objects for simple string-key dictionaries, ES6 Map for complex scenarios with various key types, and custom classes when you need specialized functionality. Map is generally preferred for true dictionary behavior.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements