JavaScript Set

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

The Set object lets you store unique values of any type, whether primitive values or object references.

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur ONCE; it is unique in the Set's collection. Distinct values are discriminated using the SameValueZero comparison algorithm.

Standard Specification About Set

Syntax

  • new Set([iterable])
  • mySet.add(value)
  • mySet.clear()
  • mySet.delete(value)
  • mySet.entries()
  • mySet.forEach(callback[, thisArg])
  • mySet.has(value)
  • mySet.values()

Parameters

ParameterDetails
iterableIf an iterable object is passed, all of its elements will be added to the new Set. null is treated as undefined.
valueThe value of the element to add to the Set object.
callbackFunction to execute for each element.
thisArgOptional. Value to use as this when executing callback.

Remarks

Because each value in the Set has to be unique, the value equality will be checked and is not based on the same algorithm as the one used in the === operator. Specifically, for Sets, +0 (which is strictly equal to -0) and -0 are different values. However, this has been changed in the latest ECMAScript 6 specification. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26) (bug 952870) and a recent nightly Chrome, +0 and -0 are treated as the same value in Set objects. Also, NaN and undefined can also be stored in a Set. NaN is considered the same as NaN (even though NaN !== NaN).



Got any JavaScript Question?