JavaScript - Set
Lachelle Zhang
Posted on May 10, 2022
Set
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' } }
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' } }
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 }
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]);
Instance properties & methods
-
size
- Returns the number of values in theSet
object.
let set = new Set([1, 2, 3, 4, 5]);
console.log(set.size); // 5
-
clear()
- Removes all elements from theSet
object.
let set = new Set([1, 2, 3, 4, 5]);
set.clear();
console.log(set); // {}
-
delete()
- Thedelete()
method removes a specified value from aSet
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 }
-
forEach()
- TheforEach()
method executes a provided function once for each value in theSet
object, in insertion order.
let set = new Set([1, 2, 3, 4, 5]);
set.forEach((element) => console.log(element)); // 1 -> 2 -> 3 -> 4 -> 5
Posted on May 10, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.