Arrays hold multiple values in a single variable. They are ordered, zero-indexed, and come with many helpful methods.
JavaScript Arrays
1) Creating Arrays
Use brackets [] or new Array().
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // apple
2) Add & Remove Elements
push()/pop() work at the end, unshift()/shift() at the start.
fruits.push('date'); // add end
fruits.pop(); // remove end
fruits.unshift('mango'); // add start
fruits.shift(); // remove start
3) Iterating Arrays
Use for, for...of, or forEach().
// for...of
for (const f of fruits) {
console.log(f);
}
// forEach
fruits.forEach((item, i) => {
console.log(i, item);
});
4) map / filter / reduce
Functional methods that return new values.
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n*2);
const evens = nums.filter(n => n%2===0);
const sum = nums.reduce((a,b) => a+b, 0);
5) includes() & indexOf()
Check if a value exists or find its position.
console.log(fruits.includes('apple')); // true
console.log(fruits.indexOf('cherry')); // 2
6) concat() & Spread
Combine arrays.
const a = [1,2];
const b = [3,4];
const c1 = a.concat(b);
const c2 = [...a, ...b];
7) sort() & reverse()
Sort alphabetically or numerically, then reverse order.
fruits.sort(); // alphabetical
fruits.reverse(); // reverse order
// numeric sort
nums.sort((a,b) => a-b);
Tip: Many array methods return a new array (
map, filter, concat) — they don’t change the original.