JS: Set Object

By Xah Lee. Date: . Last updated: .

New in ES2015.

See also: JS: the Set Object Tutorial

Set is the value of the property key "Set" of the global object. [JS: the Global Object]

console.log( window.Set === Set ); // true

Type

Set is a function.

[see JS: Value Types]

// type of Set
console.log ( typeof Set === "function" ); // true

Parent

Parent of Set is Function.prototype. [see JS: Prototype and Inheritance]

console.log ( Reflect.getPrototypeOf ( Set ) === Function.prototype ); // true

Purpose

Purpose of Set is:

  1. To create instance of “set” objects.
  2. Used as a namespace to hold general purpose methods for working with “set” objects.
  3. Holds the property key "prototype". The value of Set.prototype is the parent object of all “set” instances.

“Set” objects are collections of values.

[see JS: the Set Object Tutorial]

How Set Determines Uniqueness

The equality test used for determining whether 2 values in a set is the same as ===, except treatment of NaN (not a number).

NaN === NaN return false, but for set object, NaN is considered same as any NaN.

// equality test used for determining whether 2 values in the set is the same as ===, except treatment of NaN

// this is false
console.log(NaN === NaN); // false

// but for set object, NaN is same as any NaN
const s = new Set([NaN, NaN]);
console.log(s); // Set { NaN }

ECMAScript 2015 §Keyed Collection#sec-set-objects

Set Constructor

new Set(iterable) → create a set from values in iterable object iterable.

[see JS: Iterable]

// create a set, add value to it
const s = new Set();
s.add ("6");
s.add ("5");
s.add ("6");
console.log(s); // Set { '5', '6' }

ECMAScript 2015 §Keyed Collection#sec-set-constructor

Properties

JS Set

  1. JS: the Set Object Tutorial
  2. JS: Set Union, Intersection, Difference
  3. JS: Set Object
  4. JS: Set.prototype
  5. JS: Set.prototype.forEach
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Reference
  5. DOM Scripting
  6. SVG
  7. Blog