JavaScript Array Methods
JavaScript Arrays
Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. JavaScript arrays are zero-indexed, dynamically sized, and can hold values of mixed datatypes, though keeping them homogeneous is standard practice.
Modern Iterators:
map(): Returns a new array with the results of calling a function on every element, preserving the original array.filter(): Returns a subset of elements that match a specified boolean condition.reduce(): Executes a reducer function on each element, resulting in a single cumulative output value.
Arrays also support classic mutator methods like push() and pop() to manipulate elements at the end, and shift() and unshift() to add or remove elements at the beginning.
Modern JavaScript introduces powerful operators like the spread operator (...) to duplicate or merge arrays, and destructuring syntax to extract elements into distinct variables in a single statement.
Reducing Arrays
The reduce() method is one of JavaScript's most powerful array operations. It aggregates all array elements into a single accumulator value by running a callback function step-by-step.
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, curr) => acc + curr, 0);
console.log("Reduced Sum:", sum);const numbers = [1, 2, 3, 4, 5];
// Map numbers to squares
const squares = numbers.map(x => x * x);
console.log("Squares:", squares);
// Filter even numbers
const evens = numbers.filter(x => x % 2 === 0);
console.log("Evens:", evens);