LearnNew Collection Types in ECMAScript 6

Andrew Chalkley
writes on June 24, 2015

ECMAScript 6 is out! I covered what ECMAScript is and the new and improved syntax in this post here. But the syntax is not the only change you’ll see in ECMAScript, there are new types too – the most useful are the new types of collections, Set and Map.

Set

The Set collection type lets you store unique values. You can never add a duplicate value to a set.

Let’s say I wanted to track what courses that have been accessed today. I don’t care how many times, just that they’ve been accessed. Instead of storing them in an Array and checking if an array contains a value before adding the new value to an array like this:

var courses = [];
function addCourse(course) {
if(courses.indexOf(course) === -1) {
courses.push(course);
}
}
//User 1 visits
addCourse("jQuery Basics");
//User 2 visits
addCourse("Node.js Basics");
//User 3 visits
addCourse("jQuery Basics");
courses.forEach(value => { console.log(value)});
view raw gistfile1.js hosted with ❤ by GitHub
For a Set you could do this:
var courses = new Set();
//User 1 visits
courses.add("jQuery Basics");
//User 2 visits
courses.add("Node.js Basics");
//User 3 visits
courses.add("jQuery Basics");
courses.forEach(value => { console.log(value)});
view raw gistfile1.js hosted with ❤ by GitHub

Both examples will print out:

jQuery Basics
Node.js Basics

To get the number of items in a set you’d call the .size property, not the .length property you’d use in an array.

courses.size // 2
view raw gistfile1.js hosted with ❤ by GitHub
In addition to the add() method there’s the has() method for determining if a Set has a value in it and the delete() method for removing values.
var courses = new Set();
//User 1 visits
courses.add("jQuery Basics");
//User 2 visits
courses.add("Node.js Basics");
//User 3 visits
courses.add("jQuery Basics");
courses.has("Java Objects"); //false
courses.has("jQuery Basics"); //true
courses.delete("Node.js Basics");
course.size; // 1 (i.e. jQuery Basics);
view raw gistfile1.js hosted with ❤ by GitHub

You can also initialize a Set with an array:

var courses = new Set(["jQuery Basics", "JavaScript Basics", "jQuery Basics"]);
courses.size; // 2
view raw gistfile1.js hosted with ❤ by GitHub

 

WeakSet

A WeakSet is a collection that only stores objects and nothing else. They can’t be iterated or cycled over. For example, there is no forEach method and there isn’t a .size property either.

var contacts = new WeakSet();
var andrew = {
name: "Andrew",
email: "andrew@teamtreehouse.com"
}
var dave = {
name: "Dave",
email: "dave@teamtreehouse.com"
}
contacts.add(andrew);
contacts.add(dave);
contacts.add(andrew);
contacts.has(dave); //true
contacts.delete(dave);
contacts.has(dave); //false
view raw gistfile1.js hosted with ❤ by GitHub

References to objects are held weakly. This means that if there’s no other reference to that object in the code other than in the WeakSet itself, the garbage collector or the process by which the computer frees up space in memory, is at liberty to remove it from memory. This is why you can’t cycle over a WeakSet.

For example, I could set dave to a new object and the original dave would no longer be referenced.

var contacts = new WeakSet();
var andrew = {
name: "Andrew",
email: "andrew@teamtreehouse.com"
}
var dave = {
name: "Dave",
email: "dave@teamtreehouse.com"
}
contacts.add(andrew);
contacts.add(dave);
contacts.add(andrew);
dave = {
name: "Dave McFarland",
email: "dave@teamtreehouse.com"
}
contacts.has(dave); //false
view raw gistfile1.js hosted with ❤ by GitHub
This means that the original dave is free to be garbage collected out of the WeakSet whenever the JavaScript garbage collector comes around.

Map

Maps are just like objects but more flexible with keys. Maps are a key value pair. Unlike ECMAScript 5 objects which only allow Strings as keys, Maps allow any type, which include and is not limited to, Strings, Numbers, Arrays, Functions and Objects. A Map has two methods for setting and getting data; set() to set the key value pair and get() to retrieve the value. In this example I’m using a Map as a back bone to a social network handling the friendships. I’m using a person as a key and a Set as the value. It doesn’t make sense to have the friends as an array since you can’t be friends with people more than once.

var andrew = {
name: "Andrew",
email: "andrew@teamtreehouse.com"
}
var mary = {
name: "Mary",
email: "mary@teamtreehouse.com"
}
var dave = {
name: "Dave",
email: "dave@teamtreehouse.com"
}
var kenneth = {
name: "Kenneth",
email: "kenneth@teamtreehouse.com"
}
var friendships = new Map();
friendships.set(andrew, new Set([mary, dave]));
friendships.set(mary, new Set([andrew, kenneth, dave]));
friendships.get(andrew).has(kenneth); //false
friendships.get(andrew).add(kenneth);
friendships.get(andrew).size; //3
view raw gistfile1.js hosted with ❤ by GitHub

Another two methods you’d use are delete() to remove a key from the Map and has() to see if the key exists.

friendships.delete(andrew);
friendships.has(andrew); //false
view raw gistfile1.js hosted with ❤ by GitHub

WeakMap

The WeakMap is to Map what the WeakSet is to Set. Keys in WeakMaps must be objects, however, values can be anything.

The keys are held weakly, so if there’s no longer any reference to the key outside of the WeakMap, it’s toast! The garbage collector can free up the memory that it was using.

The WeakMap has the get(), set(), delete() and has methods, but the keys can’t be iterated over.

Conclusion

I’ve only covered the basic usage of these collections. Sets and Map are great tools to have in your developer tool belt. The WeakMap and WeakSet are handy for short-lived data manipulation, for example in a function call.

You can visit the MDN documentation pages for Set, WeakSet, Map and WeakMap to discover all you can do with these objects and the many ways you can iterate over them all.

One Response to “New Collection Types in ECMAScript 6”

  1. Duplicate values in the set doesn’t count. AWESOME!

Leave a Reply

You must be logged in to post a comment.

Want to learn more about Javascript?

Learn how to use JavaScript to add interactivity to websites.

Learn more