Set Data Structure in JavaScript

A Set data structure is used to store any number of values.

    Set considerations:
  • Only values are stored (no keys)
  • All values must be unique
let myVariable = new set();

↓ Examples ↓

//    Create the new Set
let courses = new Set();

//    Values can be passed in an array at creation
let courses = new Set(["Angular", "Node", "Java"]);

//    .add(value) will add vlaues

//    .add(value) is chainable
let courses = new Set().add("Angular").add("Node").add("Java");

//    Loop with a for...of
for (let theEntry of courses) {

//    RESULTS: Angular
//             Node                    
//             Java                

//    .size to see how large it is
console.log(courses.size); // RESULT: 3

//    .has() can be used to check if an item exists in the Set
console.log(courses.has('React')); // RESULT: false

console.log(courses.has('Angular')); // RESULT: true

//    .clear() can be used to delete all items in the Set
console.log(courses); // RESULT: Set(3) {"Angular", "Node", "Java"}


console.log(courses); // RESULT: Set(0) {}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

↑ Back to Top