| Method | Description | Example | Result |
|---|
push() | Adds element(s) to the end of an array | [1,2].push(3) | [1,2,3] |
pop() | Removes the last element | [1,2,3].pop() | [1,2] (returns 3) |
shift() | Removes the first element | [1,2,3].shift() | [2,3] (returns 1) |
unshift() | Adds element(s) to the beginning | [2,3].unshift(1) | [1,2,3] |
concat() | Joins arrays into a new one | [1,2].concat([3,4]) | [1,2,3,4] |
slice() | Returns a part of the array | [1,2,3,4].slice(1,3) | [2,3] |
splice() | Adds/removes at specific index | [1,2,3].splice(1,1,9) | [1,9,3] |
map() | Creates new array with transformed elements | [1,2,3].map(x=>x*2) | [2,4,6] |
filter() | Creates array with elements that pass a test | [1,2,3].filter(x=>x>1) | [2,3] |
reduce() | Reduces array to a single value | [1,2,3].reduce((a,b)=>a+b,0) | 6 |
Array Methods Performance
| Method | Description | Performance |
|---|
push(x) | Adds to the end | 🔥 Fast |
unshift(x) | Adds to the beginning | 🐢 Slower (O(n)) |
splice() | Inserts into the middle | 🐢 Slower (O(n)) |
concat() | Creates a new array | 🐌 Slow and not in-place |
arr[arr.length] = x | Alternative to push() | ⚡ Also very fast |
Method at
let colors = ["red", "blue", "green"];
console.log(colors.at(-1)); // green
Loop Comparison
| Feature | for…of | forEach | Traditional for |
|---|
| Syntax Simplicity | ✅ Clean & modern | ✅ Clean with callback | ❌ More verbose |
Supports break/continue | ✅ Yes | ❌ No (can't break) | ✅ Yes |
| Requires callback | ❌ No | ✅ Yes | ❌ No |
Works with Set, Map | ✅ Yes | ✅ Yes | ⚠️ Yes (manual) |
| Works with plain objects | ❌ No (not iterable) | ⚠️ No (not directly) | ⚠️ Yes (use `for...in` or keys) |
| Index access | ❌ No (value-only) | ✅ Yes (2nd param) | ✅ Yes (via `i`) |
| Performance | ⚡ Good | 🐢 Slightly slower (callbacks) | 🚀 Fastest in many cases |
| Use case | Loop over iterable values | Loop arrays when no early exit needed | Full control (index, breaks, highest perf) |
Summary:
Use for...of for readable iteration over values, forEach for concise callbacks when you don't need to break, and classic for when you need index control or max performance.