Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Maps, Sets, WeakSets, and WeakMaps

Spread the love

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at maps iteration, sets, WeakSets, and WeakMaps.

Iterating Over Maps

We can iterate over maps with the keys method to iterate over the keys.

For instance, we can write:

const m = new Map([
  ['one', 1],
  ['two', 2],
  ['three', 3],
]);

for (const k of m.keys()) {
  console.log(k);
}

Then we get:

one
two
three

from the console log.

We can iterate over the values with the values method:

for (const v of m.values()) {
  console.log(v);
}

Then we get:

1
2
3

from the console log.

We can loop through the entries with the entries method:

for (const [k, v] of m.entries()) {
  console.log(k, v);
}

Then we get:

one 1
two 2
three 3

We restructured the key and value returned from the entries method.

Converting Maps to Arrays

We can convert maps to arrays with the spread operator.

For instance, we can write:

const m = new Map([
  ['one', 1],
  ['two', 2],
  ['three', 3],
]);

const keys = [...m.keys()]

to get the keys from the map and convert it to an array.

So we get:

["one", "two", "three"]

We can also spread the map to spread the key-value pairs into a nested array of key-value pairs.

So if we have:

const m = new Map([
  ['one', 1],
  ['two', 2],
  ['three', 3],
]);

const arr = [...m]

Then we get:

[
  [
    "one",
    1
  ],
  [
    "two",
    2
  ],
  [
    "three",
    3
  ]
]

as the value of arr .

Set

A Set is a collection of values that can’t have duplicate entries.

For instance, we can write:

const s = new Set();
s.add('first');

Then we create a set with an entry.

add adds an entry.

has checks if a value exists. We can use it by writing:

s.has('first');

delete lets us delete a value:

s.delete('first');

We can also create an array, so we can write:

const colors = new Set(['red', 'green', 'blue']);

to create a set with the strings.

WeakMap and WeakSet

WeakMap and WeakSet are similar to Map and Set but are more restricted.

WeakMaps only have the has(), get(), set(), and delete() methods.

WeakSet s only have the has() , add() , and delete() methods.

Keys of WeakMap must be objects.

We can only access a WeakMap value with its key.

Values of WeakSet must be objects.

We can’t iterate over a WeakMap or WeakSet .

We can’t clear a WeakMap or WeakSet .

WeakMap s are useful when we don’t want any control over the lifecycle of the object we’re keeping with it.

It’ll automatically be garbage collected when the key is no longer available.

Conclusion

Maps, Sets, WeakMaps, and WeakSets are useful data structures that we can use with our app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *