Indexed Collections → Access by numeric index
Keyed Collections → Access by key (string, number, or object)
Weak Collections → Hold weak references (garbage-collectable)
Can contain mixed types.
Dynamically sized.
const arr = [10, "hi", true];
forEach() method:
arr.forEach((value, index) => {
console.log(index, value);
});
Refer section below → Array Methods: forEach, map, filter, reduce
Used for WebGL, audio/video manipulation, raw bytes.
Types include: Int8Array, Uint8Array, Float32Array, etc.
const bytes = new Uint8Array([255, 128, 0]);
Keys are strings or symbols.
Not ordered (though ES2015+ preserves insertion order for non-numeric keys).
const obj = { name: "Alice", age: 30 };
Keys can be any type, including objects, functions...
Maintains insertion order.
More predictable and complete than plain object for dynamic keying.
const map = new Map();
map.set("name", "Alice");
map.set({}, 123);
forEach() method:
map.forEach((value, key) => {
console.log(key, value);
});
Order is preserved.
Useful for deduplication.
const set = new Set([1, 2, 2, 3]); // → {1, 2, 3}
Note: In a Set, each value acts as its own key (internally).
Used to avoid memory leaks.
Keys MUST be objects.
Values can be anything.
Not iterable.
const wm = new WeakMap();
let obj = {};
wm.set(obj, "data");
obj = null; // entry is auto-deleted
Objects are weakly held.
Not iterable.
const ws = new WeakSet();
let user = {};
ws.add(user);
user = null; // auto-removed
They can be iterated through the for...of loop, and methods like forEach(), etc.
Common iterables:
Array
String
Map
Set
Arguments
NodeList
TypedArrays
Generators
// array
const array = ["Hello", 10, 20];
for (let ele of array) {
console.log(ele); //1st ele: Hello; 2nd ele: 10; etc.
}
// map
const map = new Map([
["1", "one"],
["2", "two"],
["3", "three"],
]);
for (let ele of map) {
console.log(ele); //1st ele: 1,one; 2nd ele: 2,two; etc.
}
const nums = [1, 2, 3];
nums.forEach(n => console.log(n * 2)); // 2 4 6
Returns: A new array of the same length.
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6]
Returns: A new array containing only elements for which the callback returns true.
const nums = [1, 2, 3, 4, 5];
const evens = nums.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
Returns: A single value (any type).
Example: Sum of an array
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 10
Example: Flatten an array of arrays
const arr = [[1,2],[3,4],[5]];
const flat = arr.reduce((acc, sub) => acc.concat(sub), []);
console.log(flat); // [1,2,3,4,5]
const nums = [1, 2, 3, 4, 5];
const result = nums
.filter(n => n % 2 === 0) // [2, 4]
.map(n => n * 10) // [20, 40]
.reduce((acc, n) => acc + n, 0); // 60