Add elements to a Dictionary in Javascript

In JavaScript, there are multiple ways to add elements to a dictionary-like structure. You can use plain objects, custom dictionary classes, or the ES6 Map object.

Using Plain Objects

The simplest approach is using JavaScript objects as dictionaries. You can add key-value pairs using bracket notation or dot notation:

const dictionary = {};

// Using bracket notation
dictionary["key1"] = "value1";
dictionary["key2"] = "value2";

// Using dot notation (for valid identifiers)
dictionary.key3 = "value3";

console.log(dictionary);
{ key1: 'value1', key2: 'value2', key3: 'value3' }

Custom Dictionary Class

You can create a custom dictionary class with a put method for adding elements:

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

const myDict = new MyDictionary();
myDict.put("key1", "value1");
myDict.put("key2", "value2");

myDict.display();
console.log(myDict.hasKey("key1"));
console.log(myDict.hasKey("key3"));
{ key1: 'value1', key2: 'value2' }
true
false

Using ES6 Map

The ES6 Map object provides a more robust dictionary implementation with the set method:

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

// Add new elements
myMap.set("key3", "value3");
myMap.set("key4", "value4");

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

// Display all entries
for (let [key, value] of myMap) {
    console.log(`${key}: ${value}`);
}
true
true
value1
key1: value1
key2: value2
key3: value3
key4: value4

Comparison

Method Key Types Performance Built-in Methods
Plain Objects Strings only Fast Limited
Custom Class Strings only Fast Custom implementation
ES6 Map Any type Good Rich API

Conclusion

Use plain objects for simple string-key dictionaries, custom classes for specific functionality, or ES6 Map for advanced features like non-string keys. Map is recommended for complex dictionary operations.

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

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements