Your Essential Guide To Map Built-in Object In Javascript

I'm Aya Bouchiha, today, we'll talk about Map built-in object.

Definition of Map Built-in Object

Map: is a data structure that stores key-value pairs, Its keys can be any datatype(primitive, objects, functions). Additionally, The original order of elements is preserved.

The advantages of Map

  • Flexible with keys, because they can be any type unlike Object (keys have to be strings and symbols)

  • Supports millions of items, 50% more than Object. A map can store 16.7 million key-value pairs where an Object can store 11.1.

  • getting easily and fastly the size of the map.

  • There are no default keys. Unlike objects that have default keys like valueOf

Map Constructor

const newMap = new Map();
const data = new Map([
    ['key', 'value'],
    [{ username: 'AyaBouchiha', job: 'full-stack developer' }, 'Aya Bouchia'],
    [true, 'isDeveloper'],
    [
        function sayHello() {
            return 'hello';
        },
        'Hello World',
    ],
]);
console.log(newMap);
console.log(data);

Ouput:

Map {}
Map {
  'key' => 'value',
  { username: 'AyaBouchiha', job: 'full-stack developer' } => 'Aya Bouchia',
  true => 'isDeveloper',
  [Function: sayHello] => 'Hello World'
}

Map.prototype.size

size: this Map property returns the number of items in a specified map.

const newMap = new Map();
const data = new Map([
    ['key', 'value'],
    [{ username: 'AyaBouchiha', job: 'full-stack developer' }, 'Aya Bouchia'],
    [true, 'isDeveloper'],
    [
        function sayHello() {
            return 'hello';
        },
        'Hello World',
    ],
]);
console.log(newMap.size); // 0
console.log(data.size); // 4

Map.prototype.get(key)

get(key): is an instance method that lets you get a value of a specified key if it exists, otherwise, It returns undefined.

const products = new Map([
    ['phone', 500],
    ['laptop', 1000],
    ['mouse', 22],
]);
console.log(products['phone']); //! undefined
console.log(products.get('phone')); // 500
console.log(products.get('something-else')); // undefined

Map.prototype.set(key, value)

set(key, value): is an instance method that lets you set or update a value for a key in a Map object

const users = new Map();
console.log(users); // Map { }
users.set('key', 'value');
users.set('aya', 'bouchiha');
console.log(users); // Map { 'key' => 'value', 'aya' => 'bouchiha' }
users.set('key', 'something'); // update the element that its key is 'key'
users['key'] = 'will not work!';
console.log(users.get('key')); // something
console.log(users.size); // 2

Map.prototype.delete(key)

delete(key): used to remove an item specified by a given key from a Map. It returns true if the item exists, otherwise, The method returns false.

const products = new Map([
    ['phone', 500],
    ['laptop', 1000],
    ['mouse', 22],
]);

console.log(products.get('phone')); // 500
console.log(products.delete('phone')); // true
console.log(products.get('phone')); // undefined
console.log(products.delete()); // false
console.log(products.delete('nothing!')); // false (because key is not found)

Map.prototype.clear()

clear(): this Map instance method deletes all key-value pairs which exist in the specified Map.

const data = new Map([
    ['key', 'value'],
    [{ username: 'AyaBouchiha', job: 'full-stack developer' }, 'Aya Bouchia'],
    [true, 'isDeveloper'],
    [
        function sayHello() {
            return 'hello';
        },
        'Hello World',
    ],
]);

console.log(data.size); // 4
data.clear();
console.log(data.size); // 0

Map.prototype.has(key):

has(key): check if the given key exists in a specified Map.

const products = new Map([
    ['phone', 500],
    ['laptop', 1000],
    ['mouse', 22],
]);
console.log(products.has('laptop')); // true
console.log(products.has()); // false
products.set(undefined, 0);
console.log(products.has()); // true
console.log(products.has('nothing!')); // false

Map.prototype.forEach(callback)

forEach(callback, thisArg): Invokes a callback for each key/value pair in the specified Map. more details

const products = new Map([
    ['phone', 500],
    ['laptop', 1000],
    ['mouse', 22],
]);

products.forEach((element) => console.log(element));
products.forEach((productPrice, productName) =>
    console.log(`you have to buy ${productPrice}$ to get a new ${productName}`),
);

Output:

500
1000
22
'you have to buy 500$ to get a new phone'
'you have to buy 1000$ to get a new laptop'
'you have to buy 22$ to get a new mouse'

Map.prototype.keys()

keys(): is a method that returns a new Iterator object that contains the keys for each element in the specified Map.

const products = new Map([
    ['phone', 500],
    ['laptop', 1000],
    ['mouse', 22],
]);

const productsKeys = products.keys();
console.log(productsKeys.next()); //  { value: 'phone', done: false }
console.log(productsKeys.next().value); // laptop
console.log(productsKeys.next().value); //  mouse
console.log(productsKeys.next()); // { value: undefined, done: true }

Map.prototype.values()

values(): is a method that returns a new Iterator object that contains the values for each element in the specified Map.

const products = new Map([
    ['phone', 500],
    ['laptop', 1000],
    ['mouse', 22],
]);

const productsValues = products.values();
console.log(productsValues.next()); //  { value: 500, done: false }
console.log(productsValues.next().value); // 1000
console.log(productsValues.next().value); // 22
console.log(productsValues.next()); // { value: undefined, done: true }

Map.prototype.entries()

entries():returns an array(iterator) [key, val] for each element in the specified Map

const products = new Map([
    ['phone', 500],
    ['laptop', 1000],
    ['mouse', 22],
]);

const productsIterator = products.entries();
console.log(productsIterator.next()); //  { value: [ 'phone', 500 ], done: false }
console.log(productsIterator.next().value); // [ 'laptop', 1000 ]
console.log(productsIterator.next().value[0]); // mouse
console.log(productsIterator.next()); // { value: undefined, done: true }

Summary

  • size: returns the number of items in a specified map.
  • get(key): lets you get a value of a specified key if it exists, otherwise, It returns undefined.
  • set(key, value): set or update a value for a key in a Map object.
  • delete(key): used to remove an item specified by a given key from a Map. It returns true if the item exists, otherwise, The method returns false.
  • clear(): deletes all key-value pairs which exist in the specified Map.
  • has(key): check if the given key exists in a specified Map.
  • forEach(callback, thisArg): Invokes a callback for each key/value pair in the specified Map.
  • keys():returns a new Iterator object that contains the keys for each element in the specified Map
  • values(): returns a new Iterator object that contains the values for each element in the specified Map.
  • entries():returns an array(iterator) [key, val] for each element in the specified Map.

References & Useful Resources

To Contact Me:

Have a great day!

51