Javascript Set()

Creates an empty set:

const games = new Set();

Creates a set from a list of values:
const games = new Set(['Super Mario Bros', 'Mario Kart']);

Adds an item to a set. Returns the set if add is successful:
games.add('Banjo-Tooie');

Deletes an item from a set. Returns a boolean depending on result:
games.delete('Super Mario Bros');

Clears all items from a set:
games.clear();

Returns the length of a set:
games.size();

Returns boolean depending on if the item is in the set:
games.has('Banjo-Tooie');

Returns all items in a set:
games.values();

Iterating through items in a set:
const iterator = games.values();
iterator.next();
for (const game of games) {
console.log(game); }

WeakSets
WeakSets can only contain objects, do not have a .clear() method and cannot be looped over. To delete an object from a WeakSet, you have to set the object to null, then Javascript’s garbage collection frees up the memory used by that object.
let student1 = {name: 'James', age: 26, gender: 'male'};
let student2 = {name: 'Julia', age: 25, gender: 'female'};
const roster = new WeakSet([student1, student2]);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.