how to use collections in javascript

There are three built-in collection types in Javascript - Array, Set, and Map.

Array

Arrays are a collection of values that are ordered and indexed. They can store any type of data, including strings, numbers, and objects.

index.tsx
// Creating an Array
let myArray = ['apple', 'banana', 'orange'];

// Accessing Array Elements
console.log(myArray[0]); // Output: apple

// Adding Elements to the Array
myArray.push('grape'); // Output: ['apple', 'banana', 'orange', 'grape']

// Removing Elements from the Array
myArray.splice(1, 1); // Output: ['apple', 'orange', 'grape']
342 chars
12 lines

Set

Sets are collections of unique values. They can store any type of data, but each value must be unique.

index.tsx
// Creating a Set
let mySet = new Set();

// Adding Elements to the Set
mySet.add('apple');
mySet.add('banana');
mySet.add('orange');
mySet.add('apple'); // Duplicate value will be ignored

// Accessing Set Elements
mySet.has('banana'); // Output: true

// Removing Elements from the Set
mySet.delete('banana'); // Output: true
328 chars
15 lines

Map

Maps are collections of key-value pairs. They can store any type of data as both keys and values.

index.tsx
// Creating a Map
let myMap = new Map();

// Adding Elements to the Map
myMap.set('fruit1', 'apple');
myMap.set('fruit2', 'banana');
myMap.set('fruit3', 'orange');

// Accessing Map Elements
console.log(myMap.get('fruit1')); // Output: apple

// Removing Elements from the Map
myMap.delete('fruit2'); // Output: true
317 chars
14 lines

gistlibby LogSnag