DEV Community

Cover image for JavaScript - Set
Lachelle Zhang
Lachelle Zhang

Posted on • Edited on

JavaScript - Set

Set

Set - MDN

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

let set = new Set();
set.add(1);
set.add({ name: "kitty" });
console.log(set); // { 1, { name: 'kitty' } }
Enter fullscreen mode Exit fullscreen mode

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.

// A value in the Set may only occur once
let set = new Set();
set.add(1);
set.add({ name: "kitty" });
set.add(1);
console.log(set); // { 1, { name: 'kitty' } }
Enter fullscreen mode Exit fullscreen mode

Value equality: 1.+0 & -0 are the same(ES6); 2.NaN & undefined can also be stored in a Set. All NaN values are equated(NaN is considered the same as NaN, even though NaN !== NaN)

//1.`+0` & `-0` are the same(ES6)
let set1 = new Set();
set1.add(+0);
set1.add(-0);
console.log(set1); // { 0 }
//2.`NaN` & `undefined` can also be stored in a Set. All `NaN` values are equated(NaN is considered the same as NaN, even though NaN !== NaN)
let set2 = new Set();
set2.add(NaN);
set2.add(undefined);
set2.add(NaN);
console.log(set2); // { NaN, undefined }
Enter fullscreen mode Exit fullscreen mode

Constructor - Set()
The Set constructor lets you create Set objects that store unique values of any type, whether primitive values or object references.
Syntax - new Set(iterable)

let set = new Set([1, 2, 3, 4, 5]);
Enter fullscreen mode Exit fullscreen mode

Instance properties & methods

  • size - Returns the number of values in the Set object.
  let set = new Set([1, 2, 3, 4, 5]);
  console.log(set.size); // 5
Enter fullscreen mode Exit fullscreen mode
  • clear() - Removes all elements from the Set object.
  let set = new Set([1, 2, 3, 4, 5]);
  set.clear();
  console.log(set); // {}
Enter fullscreen mode Exit fullscreen mode
  • delete() - The delete() method removes a specified value from a Set object, if it is in the set.
  let set = new Set([1, 2, 3, 4, 5]);
  set.delete(1);
  console.log(set); // { 2,3,4,5 }
Enter fullscreen mode Exit fullscreen mode
  • forEach() - The forEach() method executes a provided function once for each value in the Set object, in insertion order.
  let set = new Set([1, 2, 3, 4, 5]);
  set.forEach((element) => console.log(element)); // 1 -> 2 -> 3 -> 4 -> 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)