Limitations With Array
Arrays don't enforce uniqueness of items. Diplicate entries are allowed.
Using Sets
let tags = new Set() ; tags.add('Javascript'); tags.add('Programming'); tags.add('Web'); console.log(`Total items ${tags.size}`);
Sets and for...of
let tags = new Set(); tags.add("JavaScript"); tags.add("Programming"); tags.add("Web"); for( let tag of tags ){ console.log(`Tag: ${tag}`); }
Sets and Destructuring
let tags = new Set(); tags.add("JavaScript"); tags.add("Programming"); tags.add("Web"); let [first] = tags; console.log( `First tag: ${first}` );
WeakSets
The WeakSet
is a more memory efficient type of Set
where only objets are allowed to be stored.
WeakSets in Action
let allPosts = new WeakSet(); let post1 = { title: "ES2015" }; let post2 = { title: "CoffeeScript" }; let post3 = { title: "TypeScript" }; allPosts.add( post1 ); allPosts.add( post2 ); allPosts.add( post3 );
How can we query the allPosts
WeakSet to determine whether it has the post2
object?
allPosts.has(post2);