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:

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

Clears all items from a set:

Returns the length of a set:

Returns boolean depending on if the item is in the set:

Returns all items in a set:

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

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]);


Leave a Reply

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

You are commenting using your 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.