By Ran Bar-Zik | 3/9/2018 | General |Beginners

ECMAScript 6 - Set and Map

ECMAScript 6 - Set and Map

Saving data in JavaScript always used to  be carried out in objects, or arrays of objects. Before ES6 JavaScript lacked the map type of object (a structure designed to save data in most languages). Because of this, we had to use objects in order to save data. For example:

var o = {1: 'a', 2: 'b'};

A few problems arise due to the lack of a proper map object. The first of which is that there are a few operations we carry out on objects that are likely to be problematic because of the prototype chain and objects that are likely to inherit attributes from our parent object. This is really problematic when it comes to iterations (we saw this before with forEach loops on objects), and estimating the size of objects.

 

For instance, object size:

Object.size = function(obj) {

   var size = 0, key;

   for (key in obj) {

       if (obj.hasOwnProperty(key)) size++;

   }

   return size;

};

 

// Get the size of an object

var size = Object.size(myArray);

There is also the problem of keys that always have to be text:

 

var o = {1: 'a', 2: 'b'};

o[1] // a

o['1'] // a

In short, using a map object is possible but problematic. Thankfully, it’s just for this type of problem that we have ECMAScript 6 and the map object. We use instance on a map with new, and there are a few basic methods: get and set which we use for entering and extracting data according to key/value, and of course has that returns a boolean (true or false) if the key exists. Here’s your long awaited example:

 

var myMap = new Map();

  

myMap.set('foo', 123);

var a = myMap.get('foo');

console.log(a); //123

console.log(myMap.has('foo')); //true

myMap.delete('foo')

console.log(myMap.has('foo')); //false

Of course anything, including an object, can be a key—regardless if it is a number or text string. For example:

var myMap = new Map();

  

myMap.set(1, 'some value');

console.log(myMap.has(1)); //true

console.log(myMap.has('1')); //false

Other methods include size which returns the size of the map, and clear the cleans it. Here is an example where we are putting in members at the creation of the map:

var myMap = new Map([

 [1, 'some value'],

 [2, 'another value']

 ]);

  

console.log(myMap.size); //2

myMap.clear();

console.log(myMap.size); //0

And of course it’s easy to do iterations on maps. Here’s how we do it with a for of and keys:

 

var myMap = new Map([

 [1, 'some value'],

 [2, 'another value']

 ]);

  

for (var key of myMap.keys()) {

   console.log(key);

} //1, 2

And also values:

var myMap = new Map([

 [1, 'some value'],

 [2, 'another value']

 ]);

  

for (var value of myMap.values()) {

   console.log(value);

} //"some value", "another value"

The sharp-eyed among you will notice that I used two attributes here—keys and values that produce an array of keys and values. You can get entries that are an array of the key and the value:

 

var myMap = new Map([

 [1, 'some value'],

 [2, 'another value']

 ]);

  

for (var entry of myMap.entries()) {

   console.log(entry[0], entry[1]);

} //1 "some value", 2 "another value"

WeakMap

It can be difficult to understand the WeakMap without understanding memory leaks in JavaScript. In principal, weakmap is just like map, except that it only takes objects as keys and you can’t iterate on it. In other words, all the methods are there, but you won’t be able to run an iteration on it. So what do we need the weakmap for? To understand why we need it we have to first get firmiliar with memory leaks. Imagine a situation like this: we have some DOM elements. Some of them are saved in maps for various reasons. If we delete them from the DOM, we’d expect that JavaScript would clear the space that those elements took up in the memory. But a map will save the reference to these objects despite the fact that they’ve been erased! This is because the garbage collector doesn’t understand that it supposed to erase them.

 

So it’s for this exact reason that we have a weakmap—the keys of these maps are ‘weak’ and can’t stop whatever goes into them from just disappearing. It’s pretty hard to demonstrate it, but I hope that this example will be clear:

 In general, WeakMap is like a map, but with objects that are keys and without size in iteration. If you are storing data in objects and afterward erasing them then there’s a good chance that WeakMap will come in handy.

 

WeakSet and Set

Like map, set is also a data structure that until ES6 wasn’t part of JavaScript. Long story short, its job is to contain values and we can verify if a particular value is inside. This is useful in all kinds of situations and particularly for creating lists for continuous use. If for instance we have a list of names that users add, that we send to the server, but say for example we need to make sure there’s no duplication, then set would be perfect.

var set = new Set();

set.add('red')

console.log(set.has('red')); //true

set.delete('red')

console.log(set.has('red')); //false

We can also do iteration as well. There are no keys of course, just values.

var set = new Set(['red', 'green', 'blue']);

for (var x of set) {

   console.log(x); //red, green, blue

}

There is also the clear method for completely clearing the set, and the size attribute for the size of the set.

 

Just like we have WeakMap, we also have WeakSet that has three methods: set, has, and delete. WeakSet also allows the memory to be released if the objects inside it have been erased.

 

Previous article: Text Strings and Dates

Next article: For of Loops

 

About the author: Ran Bar-Zik is an experienced web developer whose personal blog, Internet Israel, features articles and guides on Node.js, MongoDB, Git, SASS, jQuery, HTML 5, MySQL, and more. Translation of the original article by Aaron Raizen.

By Ran Bar-Zik | 3/9/2018 | General

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now