Thursday, December 22, 2016

JavaScript Evolution ECMAScript 6 - Sets

Before we understand the needs to use Sets, let's go back to understand Array limitation.

Array in JavaScript is very simple to use, but 1 thing they don't do is Array doesn't enforce uniqueness of items. Duplicate entries are allowed.
let tags = [];
tags.push ("JavaScript");
tags.push("Programming");
tags.push("Web");
tags.push("Web");

console.log(tags.length); // Return 4
If we want to prevent duplicate entry to be added into a collection, instead of Array, we can use Set. Set object stores uniques values of any types, where primitives values or object references.
let tags = new Set();
tags.add("JavaScript");
tags.add("Programming");
tags.add({version: "2015"}); // We can add object
tags.add("Web");
tags.add("Web"); // Duplicate entry are ignored.

console.log(tags.size); // Return 4
Set object is iterative, which means they can be used with for...of and destructuring.
for (let tag of tags) {
  console.log(tag);
}

// Return:
// JavaScript
// Programming
// {version: "2015"}
// Web

let [a, b,c, d] = tags;
console.log(a ,b, c, d);

// Return JavaScript, Programming, {version: "2015"}, Web

No comments:

Post a Comment