Arrays
An Array in JavaScript is a special type of object used to store ordered collections of values. These values can be of any type — numbers, strings, Booleans, objects, other arrays, or even functions. Arrays make it easy to store, access, and manipulate multiple values using indices.
Why Use Arrays?
Arrays are useful when you need to:
- Store multiple related values in a single variable.
- Perform operations on a collection of values (sorting, filtering, mapping, etc.).
- Iterate through data using loops.
- Keep your code organized and maintainable.
Example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits); // ["apple", "banana", "orange"]
Essential Methods
Adding / Removing Elements
- push(...items): Add to the end. Returns new length.
- pop(): Remove from the end. Returns removed element.
- unshift(...items): Add to the start. Returns new length.
- shift(): Remove from the start. Returns removed element.
- splice(start, deleteCount, ...items): Add/remove at specific index.
arr.push(2); // [1, 'hello', { id: 1 }, 2]
arr.splice(1, 1, 'world'); // [1, 'world', { id: 1 }, 2]
Iterating / Transforming
forEach(callback): Run a function for each element.
arr.forEach(item => console.log(item));
map(callback): Create a new array with transformed elements.
let doubled = [1, 2, 3].map(x => x * 2); // [2, 4, 6]
filter(callback): Create a new array with elements passing a test.
let evens = [1, 2, 3, 4].filter(x => x % 2 === 0); // [2, 4]
reduce(callback, initialValue): Reduce to a single value.
let sum = [1, 2, 3].reduce((acc, x) => acc + x, 0); // 6
Searching / Sorting
find(callback): Return the first element matching the condition.
let found = arr.find(x => x === 'world'); // 'world'
includes(value): Check if a value exists.
arr.includes(1); // true
sort(compareFn): Sort in place. Use compareFn
for numbers.
[3, 1, 2].sort((a, b) => a - b); // [1, 2, 3]
Other Useful Methods
- slice(start, end): Extract a portion (non-mutating).
- concat(...arrays): Merge arrays (non-mutating).
- join(separator): Convert array to string.
let part = arr.slice(1, 3); // ['world', { id: 1 }]
arr.join(', '); // '1, world, [object Object], 2'
Advanced Features
Spread Operator: Copy or merge arrays.
let copy = [...arr]; // Shallow copy
let merged = [...arr, ...[3, 4]];
- Destructuring: Extract elements into variables.
let [first, second] = arr; // first = 1, second = 'world'
Sparse Arrays: Gaps are filled with undefined
.
let sparse = [1, , 3]; // [1, undefined, 3]