Creating Arrays
Arrays store ordered collections. Create them with literals or the Array constructor.
const fruits = ["apple", "banana", "cherry"];
const numbers = new Array(1, 2, 3);
const empty = [];
console.log(fruits[0]); // apple
console.log(numbers[1]); // 2
console.log(empty.length); // 0
Try it Yourself โ
push and pop
push adds items to the end. pop removes the last item.
const stack = [];
stack.push("first");
stack.push("second");
stack.push("third");
console.log(stack); // ["first", "second", "third"]
const last = stack.pop();
console.log(last); // third
console.log(stack); // ["first", "second"]
Try it Yourself โ
shift and unshift
unshift adds items to the front. shift removes the first item.
const queue = ["second", "third"];
queue.unshift("first");
console.log(queue); // ["first", "second", "third"]
const first = queue.shift();
console.log(first); // first
console.log(queue); // ["second", "third"]
Try it Yourself โ
Finding Elements
indexOf, includes, find, and findIndex search arrays.
const data = [10, 20, 30, 40, 50];
console.log(data.indexOf(30)); // 2
console.log(data.includes(100)); // false
const found = data.find(n => n > 25);
console.log(found); // 30
const idx = data.findIndex(n => n > 25);
console.log(idx); // 2
Try it Yourself โ
map
map creates a new array by transforming each element.
const prices = [10, 20, 30];
const withTax = prices.map(p => p * 1.1);
console.log(withTax); // [11, 22, 33]
Try it Yourself โ
filter
filter returns a new array with only elements that pass the test.
const numbers = [5, 12, 8, 130, 44];
const big = numbers.filter(n => n >= 50);
console.log(big); // [130]
Try it Yourself โ
reduce
reduce accumulates values into a single result.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, n) => acc + n, 0);
const product = numbers.reduce((acc, n) => acc * n, 1);
console.log(sum); // 15
console.log(product); // 120
Try it Yourself โ
Spread Operator
The spread operator ... expands an array into individual elements.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
const copy = [...arr1];
console.log(copy); // [1, 2, 3]
Try it Yourself โ
Array Destructuring
Destructuring unpacks array values into variables.
const rgb = [255, 128, 64];
const [red, green, blue] = rgb;
console.log(red); // 255
console.log(green); // 128
console.log(blue); // 64
const [first, , third] = rgb;
console.log(first); // 255
console.log(third); // 64
Try it Yourself โ