Arrays

An array is a special variable that can hold more than one value at a time. Instead of declaring separate variables for each value, you store them together in a single array.

Arrays in JavaScript can hold any type of data — numbers, strings, booleans, objects, or even other arrays. They are ordered, meaning each item has a fixed position.

javascript

let fruits = ["apple", "banana", "cherry"];

console.log(fruits); // ["apple", "banana", "cherry"]

Without arrays, you would need a separate variable for every value. That quickly becomes hard to manage, especially when you do not know how many values you will have ahead of time.

Arrays let you store, loop through, and manage a collection of values using a single variable name. This makes your code shorter, cleaner, and easier to maintain.

javascript

// Without arrays - messy
let fruit1 = "apple";
let fruit2 = "banana";
let fruit3 = "cherry";

// With arrays - clean
let fruits = ["apple", "banana", "cherry"];

There are two common ways to create an array in JavaScript: using an array literal or using the Array constructor.

The array literal syntax is recommended because it is simpler and easier to read. The new Array() constructor is less common but still valid.

javascript

// Array Literal (recommended)
let colors = ["red", "green", "blue"];

// Array Object using new Array()
let numbers = new Array(1, 2, 3, 4, 5);

console.log(colors);  // ["red", "green", "blue"]
console.log(numbers); // [1, 2, 3, 4, 5]

Note that new Array(3) creates an empty array with 3 slots, not an array containing the number 3. Use the literal syntax to avoid this confusion.

Every element in an array has a numbered position called an index. Array indexes start at 0, so the first element is at index 0, the second at index 1, and so on.

You can read or update any element by referring to its index using square bracket notation.

javascript

let fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]); // apple
console.log(fruits[1]); // banana
console.log(fruits[2]); // cherry

// Update an element
fruits[1] = "mango";
console.log(fruits); // ["apple", "mango", "cherry"]

The length property returns the total number of elements in an array. It always equals the highest index plus one.

You can also use length to access the last element of an array, since the last index is always length - 1.

javascript

let fruits = ["apple", "banana", "cherry"];

console.log(fruits.length); // 3

// Access the last element
console.log(fruits[fruits.length - 1]); // cherry

Arrays can be declared using let, const, or var. Using const is the most common choice because it prevents the variable from being reassigned, while still allowing you to modify the array contents.

javascript

// Using const (recommended)
const scores = [10, 20, 30];
scores.push(40); // OK - modifying contents is allowed
// scores = [1, 2]; // Error - reassigning is not allowed

// Using let
let names = ["Alice", "Bob"];
names = ["Charlie"]; // OK - reassigning is allowed with let

// Empty array
const empty = [];

You can loop through an array to read or process each element. The two most common ways are the for loop and the forEach method.

javascript

const fruits = ["apple", "banana", "cherry"];

// Using a for loop
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// apple
// banana
// cherry

// Using forEach
fruits.forEach(function(fruit) {
  console.log(fruit);
});
// apple
// banana
// cherry

The for loop gives you access to the index, which is useful when you need to know the position. forEach is cleaner when you just need to do something with each element.

JavaScript provides many built-in methods on arrays to make common tasks easy. These methods let you add, remove, search, transform, and combine arrays without writing complex logic from scratch.

Here is a quick overview of the most commonly used array methods:

  • push() — add to end
  • pop() — remove from end
  • unshift() — add to beginning
  • shift() — remove from beginning
  • toString() — convert to string
  • join() — join elements with a separator
  • concat() — merge arrays
  • splice() — add or remove at a position
  • slice() — extract a portion
  • sort() — sort elements
  • reverse() — reverse the order
  • forEach() — loop through elements
  • at() — access element by index (supports negative index)
  • map() — transform each element
  • filter() — keep elements that match a condition
  • reduce() — combine all elements into one value
  • find() — find first matching element
  • findIndex() — find index of first match
  • some() — check if any element matches
  • every() — check if all elements match
  • flat() — flatten nested arrays
  • flatMap() — map then flatten

The push() method adds one or more elements to the end of an array and returns the new length of the array.

javascript

const fruits = ["apple", "banana"];

fruits.push("cherry");
console.log(fruits); // ["apple", "banana", "cherry"]

// Push multiple items
fruits.push("mango", "grape");
console.log(fruits); // ["apple", "banana", "cherry", "mango", "grape"]

The pop() method removes the last element from an array and returns that removed element. It modifies the original array.

javascript

const fruits = ["apple", "banana", "cherry"];

const removed = fruits.pop();
console.log(removed); // cherry
console.log(fruits);  // ["apple", "banana"]

The unshift() method adds one or more elements to the beginning of an array and returns the new length.

javascript

const fruits = ["banana", "cherry"];

fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "cherry"]

The shift() method removes the first element from an array and returns it. The remaining elements shift down by one index.

javascript

const fruits = ["apple", "banana", "cherry"];

const first = fruits.shift();
console.log(first);  // apple
console.log(fruits); // ["banana", "cherry"]

The toString() method converts an array to a comma-separated string. It does not modify the original array.

javascript

const fruits = ["apple", "banana", "cherry"];

console.log(fruits.toString()); // "apple,banana,cherry"

The join() method joins all elements of an array into a string. You can pass a custom separator as an argument. If no separator is given, a comma is used by default.

javascript

const fruits = ["apple", "banana", "cherry"];

console.log(fruits.join());      // "apple,banana,cherry"
console.log(fruits.join(" - ")); // "apple - banana - cherry"
console.log(fruits.join(""));    // "applebananacherry"

The concat() method merges two or more arrays and returns a new array. It does not modify the original arrays.

javascript

const a = [1, 2];
const b = [3, 4];
const c = [5, 6];

const result = a.concat(b, c);
console.log(result); // [1, 2, 3, 4, 5, 6]

The splice() method can add, remove, or replace elements at a specific position in an array. It modifies the original array and returns the removed elements.

Syntax: splice(startIndex, deleteCount, item1, item2, ...)

javascript

const fruits = ["apple", "banana", "cherry", "mango"];

// Remove 1 element at index 1
const removed = fruits.splice(1, 1);
console.log(removed); // ["banana"]
console.log(fruits);  // ["apple", "cherry", "mango"]

// Insert at index 1 without removing
fruits.splice(1, 0, "grape");
console.log(fruits);  // ["apple", "grape", "cherry", "mango"]

The slice() method returns a shallow copy of a portion of an array between a start and end index. It does not modify the original array.

The end index is not included in the result. If no end is given, it goes to the end of the array.

javascript

const fruits = ["apple", "banana", "cherry", "mango", "grape"];

console.log(fruits.slice(1, 3)); // ["banana", "cherry"]
console.log(fruits.slice(2));    // ["cherry", "mango", "grape"]
console.log(fruits);             // original is unchanged

The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order.

For sorting numbers correctly, you need to pass a comparison function. Without it, numbers are sorted as strings, which can give unexpected results.

javascript

// Sorting strings
const fruits = ["cherry", "apple", "banana"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry"]

// Sorting numbers
const nums = [10, 2, 30, 5];
nums.sort((a, b) => a - b); // ascending
console.log(nums); // [2, 5, 10, 30]

The reverse() method reverses the order of the elements in an array in place. The first element becomes the last, and the last becomes the first.

javascript

const nums = [1, 2, 3, 4, 5];

nums.reverse();
console.log(nums); // [5, 4, 3, 2, 1]

The forEach() method calls a provided function once for each element in an array. It does not return a new array and cannot be stopped early like a regular loop.

javascript

const nums = [1, 2, 3];

nums.forEach((num, index) => {
  console.log(index + ": " + num);
});
// 0: 1
// 1: 2
// 2: 3

The at() method returns the element at the given index. It supports negative indexes, where -1 refers to the last element, -2 the second to last, and so on.

javascript

const fruits = ["apple", "banana", "cherry"];

console.log(fruits.at(0));  // apple
console.log(fruits.at(-1)); // cherry (last element)
console.log(fruits.at(-2)); // banana

The map() method creates a new array by applying a function to every element of the original array. The original array is not changed.

javascript

const nums = [1, 2, 3, 4];

const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
console.log(nums);    // [1, 2, 3, 4] - original unchanged

The filter() method creates a new array with only the elements that pass a given condition (where the callback returns true). The original array is not modified.

javascript

const nums = [1, 2, 3, 4, 5, 6];

const evens = nums.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]

The reduce() method processes each element of the array and accumulates them into a single value. It takes a callback function and an optional initial value.

The callback receives the accumulator (the running result) and the current value on each iteration.

javascript

const nums = [1, 2, 3, 4, 5];

const sum = nums.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

The find() method returns the first element that satisfies the provided condition. If no element matches, it returns undefined.

javascript

const nums = [3, 7, 12, 5, 20];

const firstBig = nums.find(n => n > 10);
console.log(firstBig); // 12

The findIndex() method returns the index of the first element that satisfies the condition. If no match is found, it returns -1.

javascript

const nums = [3, 7, 12, 5, 20];

const index = nums.findIndex(n => n > 10);
console.log(index); // 2

The some() method checks if at least one element in the array satisfies the condition. It returns true or false.

javascript

const nums = [1, 3, 5, 8];

console.log(nums.some(n => n % 2 === 0)); // true  (8 is even)
console.log(nums.some(n => n > 100));     // false

The every() method checks if all elements in the array satisfy the condition. It returns true only if every element passes, otherwise false.

javascript

const nums = [2, 4, 6, 8];

console.log(nums.every(n => n % 2 === 0)); // true  (all are even)
console.log(nums.every(n => n > 5));       // false (2 and 4 are not)

The flat() method creates a new array with all nested sub-arrays flattened up to the specified depth. The default depth is 1.

javascript

const nested = [1, [2, 3], [4, [5, 6]]];

console.log(nested.flat());    // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2));   // [1, 2, 3, 4, 5, 6]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5, 6]

The flatMap() method maps each element using a function and then flattens the result by one level. It is equivalent to calling map() followed by flat(1).

javascript

const sentences = ["hello world", "foo bar"];

const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["hello", "world", "foo", "bar"]

Arrays are one of the most used data structures in JavaScript. Here is a quick recap of what we covered:

  • An array stores multiple values in a single variable.
  • Array indexes start at 0.
  • Use const to declare arrays when the reference should not change.
  • push / pop add or remove from the end.
  • unshift / shift add or remove from the beginning.
  • splice modifies the array in place; slice returns a copy.
  • map, filter, and reduce are the most powerful tools for transforming data.
  • find and findIndex search for elements by condition.
  • some and every check conditions across the array.
  • flat and flatMap handle nested arrays.