Welcome to our free Advanced JavaScript Programming tutorial. This tutorial is based on Webucator's Advanced JavaScript Programming course.

Contact Us or call 1-877-932-8228


Another useful JavaScript object is the Set. Unlike a Map, a Set object can contain no duplicate items: it stores only unique values, of any type. As with Maps, we can iterate over a Set object in insertion order.

Common Set Properties
Property Description Example
constructor Creates a Set theSet = new Set()
size Returns the number of values theSet.size
Common Set Methods
Method Description Example
add Appends a new value, if the value does not already exist in the set theSet.add('abc')
clear Removes all values theSet.clear()
delete Removes a specified value theSet.delete('abc')
forEach Iterates over the Set theSet.forEach(function (item) { //do something with each item })
has Returns true if is element is contained in the set theSet.has(20) // returns true if 20 exists in theSet

We'll take a look now at an example:

Code Sample:

<!DOCTYPE html>
	<meta charset="utf-8">
		var mySet = new Set();
		var arr = ['one', 'two', 'three'];
		mySet.add(1); // won't be added, as 1 already exists as an element

		document.write('<p>Size of set: ' + mySet.size + '</p>');
		document.write('<p>Does mySet have element 1?: ' + mySet.has(1) + '</p>');
		document.write('<p>Does mySet have element arr?: ' + mySet.has(arr) + '</p>');
		document.write('<p>Does mySet have element "blue?: ' + mySet.has("blue") + '</p>');
		document.write('<p>(mySet cleared)</p>');
		document.write('<p>Size of set: ' + mySet.size + '</p>');

Code Explanation

We create a new Set on line 10 and add values to it with the add method. Note that adding the value 1 on line 15 has no effect, since 1 was already added previously.

Next, we'll ask you to try out using Map and Set in the following exercise:


This tutorial is based on Webucator's Advanced JavaScript Programming Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.