helpermethod helpermethod - 6 months ago 10
Javascript Question

Ways to create a Set in JavaScript?

In Eloquent JavaScript, Chapter 4, a set of values is created by creating an object and storing the values as property names, assigning arbitrary values (e.g. true) as property values. To check if the value is already contained in the set, the

in
operator is used:

var set = {};

if (!'Tom' in set) {
set.Tom = true;
}


Is this idiomatic JavaScript? Wouldn't be using an array even better?

var set = [];

if (!'Tom' in set) {
set.push = 'Tom';
}

Answer

Sets are now available in ES2015 (aka ES6, i.e. EcmaScript 6). ES6 has been the current standard for JavaScript since June 2015.

ECMAScript 6 has the data structure Set which works for arbitrary values, is fast and handles NaN correctly. -Axel Rauschmayer, Exploring ES6

First two examples from Axel Rauschmayer's book Exploring ES6:

Managing single elements:

> let set = new Set();
> set.add('red')

> set.has('red')
true
> set.delete('red')
true
> set.has('red')
false

Determining the size of a Set and clearing it:

> let set = new Set();
> set.add('red')
> set.add('green')

> set.size
2
> set.clear();
> set.size
0

I would check out Exploring ES6 if you want to learn more about Sets in JavaScript. The book is free to read online, but if you would like to support the author Dr. Axel Rauschmayer you can purchase the book for around $30.

If you want to use Sets and ES6 now you can use Babel, the ES6 to ES5 transpiler, and its polyfills.