Arrays
Arrays
Section titled “Arrays”What it means
Section titled “What it means”Arrays are ordered collections of values. JavaScript arrays are dynamic (grow/shrink automatically) and can hold mixed types. Modern array methods (map, filter, reduce, etc.) enable functional programming patterns.
Examples
Section titled “Examples”// Creating arraysconst nums = [1, 2, 3, 4, 5];const mixed = [1, "two", true, null];const empty = [];const from = Array.from("hello"); // ['h','e','l','l','o']
// Accessing elementsconsole.log(nums[0]); // 1console.log(nums.length); // 5console.log(nums.at(-1)); // 5 (last element)
// Common methodsnums.push(6); // add to endnums.pop(); // remove from endnums.unshift(0); // add to startnums.shift(); // remove from start
// Array methods (functional)const doubled = nums.map(n => n * 2);const evens = nums.filter(n => n % 2 === 0);const sum = nums.reduce((acc, n) => acc + n, 0);
// Finding elementsconst found = nums.find(n => n > 3); // 4const index = nums.findIndex(n => n > 3); // 3const has = nums.includes(3); // true
// Transformingconst joined = nums.join(", "); // "1, 2, 3, 4, 5"const sliced = nums.slice(1, 3); // [2, 3]const sorted = [...nums].sort((a, b) => b - a); // [5, 4, 3, 2, 1]Common mistake
Section titled “Common mistake”Modifying array while iterating with forEach:
const arr = [1, 2, 3, 4, 5];
// BAD - modifying during iteration causes unexpected behaviorarr.forEach((val, i) => { if (val % 2 === 0) arr.splice(i, 1); // Don't do this!});
// GOOD - create new arrayconst odds = arr.filter(val => val % 2 !== 0);Fix: Use filter to create a new array instead of mutating during iteration.
Quick practice
Section titled “Quick practice”-
How do you remove the last element from an array?
Answer
`arr.pop()` - removes and returns the last element. -
What does
[1, 2, 3].map(x => x * 2)return?Answer
`[2, 4, 6]` - map transforms each element. -
How do you combine two arrays?
Answer
`const combined = [...arr1, ...arr2]` or `arr1.concat(arr2)`