How is a JavaScript hash map implemented?

Should you try this class Map:

var myMap = new Map();

// setting the values
myMap.set("1", 'value1');
myMap.set("2", 'value2');
myMap.set("3", 'value3');

console.log(`Map size: ${myMap.size}`); // 3

// getting the values
console.log(`Key: "1", Value: ${myMap.get("1")}`);    // "value associated with "value1"
console.log(`Key: "2", Value: ${myMap.get("2")}`);    // "value associated with "value2"
console.log(`Key: "3", Value: ${myMap.get("3")}`);    // "value associated with "value3"

Notice: key and value can be any type.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map


every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:

var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)

2020 Update:

javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.


Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

JavaScript objects cannot be implemented purely on top of hash maps.

Try this in your browser console:

var foo = {
    a: true,
    b: true,
    z: true,
    c: true
}

for (var i in foo) {
    console.log(i);
}

...and you'll recieve them back in insertion order, which is de facto standard behaviour.

Hash maps inherently do not maintain ordering, so JavaScript implementations may use hash maps somehow, but if they do, it'll require at least a separate index and some extra book-keeping for insertions.

Here's a video of Lars Bak explaining why v8 doesn't use hash maps to implement objects.