Home
 › Learn
 › JavaScript

Comprehensive Guide to JavaScript Arrays and Built-in Methods

JavaScript arrays are one of the most fundamental and versatile data structures in the language, allowing developers to store, access, and manipulate collections of elements efficiently. With a rich set of built-in methods like push(), pop(), slice(), and forEach(), arrays provide powerful tools for adding, removing, transforming, and iterating through data, making them essential for everything from simple list management to complex data processing tasks.

Updated At: December 2021
Comprehensive Guide to JavaScript Arrays and Built-in Methods

Here is the complete list of JavaScript array methods categorized by their primary functions.

Array Creation and Identification

This section covers the foundational methods used to create new arrays or identify array types in JavaScript.

Array() Constructor

The Array() constructor creates a new array. It can be invoked with or without the new keyword — both produce the same result.

  • If called with a single numeric argument, it creates an array with that length (empty slots).

  • With multiple arguments, it creates an array containing those values.

Syntax:

new Array();
new Array(element1, element2, ..., elementN);
new Array(arrayLength);

Examples:

// Empty array
const empty = new Array(); // []

// Array with length 3 (empty slots)
const fixedSize = new Array(3); // [ <3 empty items> ]

// Array with predefined elements
const fruits = new Array("Apple", "Banana"); // ["Apple", "Banana"]

// Without using 'new'
const cities = Array("Paris", "Berlin"); // Works the same way

If you pass one number (e.g., new Array(2)), it sets the array length, but doesn't fill it with undefined. Those are empty slots, as noted by MDN.

Array.from()

Array.from() creates a new shallow-copied Array instance from an iterable (like a string, Set, or Map) or an array-like object (like arguments). It also takes an optional mapping function to modify elements while creating the array.

Syntax:

Array.from(arrayLike, mapFn?, thisArg?);

Examples:

// From string
Array.from("hello");
// ["h", "e", "l", "l", "o"]

// From Set
const letters = new Set(["a", "b", "c"]);
Array.from(letters);
// ["a", "b", "c"]

// With mapping function
Array.from([1, 2, 3], x => x * 2);
// [2, 4, 6]

// Generate a range
const range = Array.from({ length: 5 }, (_, i) => i + 1);
// [1, 2, 3, 4, 5]

This is ideal when transforming iterables into arrays with a single step.

Array.of()

Creates a new Array instance with the provided elements, avoiding the numeric ambiguity of the Array() constructor.

Syntax:

Array.of(element1, element2, ..., elementN);

Examples:

Array.of(7);       // [7]
Array(7);          // Empty array with length 7
Array.of(1, 2, 3); // [1, 2, 3]
Array.of();        // []

Why use Array.of()?
⁠When you intend to explicitly create arrays containing numeric values and not arrays of empty slots, this method removes confusion between creating an array with a length and one with actual values

Array.isArray()

Determines if a given value is an array.
Useful when checking data types before performing array operations.

Syntax:

Array.isArray(value);

Examples:

Array.isArray([1, 2, 3]); // true
Array.isArray({});        // false
Array.isArray("hello");   // false
Array.isArray(new Array()); // true
Array.isArray is especially handy when working with APIs or dynamic data, ensuring you can differentiate between arrays and objects.

length

Every array has a length property that reflects the count of elements, including empty slots.

Examples:

const colors = ["red", "green", "blue"];
console.log(colors.length); // 3

colors.length = 2; // Truncates the array
console.log(colors); // ["red", "green"]

colors.length = 5; // Expands with empty slots
console.log(colors); // ["red", "green", <3 empty items>]
The length property is writable — reducing it truncates the array, while increasing it creates sparse arrays with empty slots

constructor

Returns the constructor function that created the array instance — usually Array() itself.

Syntax:

array.constructor;

Example:

const numbers = [1, 2, 3];
console.log(numbers.constructor); // function Array() { [native code] }
This is useful for verifying if an object is constructed by Array(), though Array.isArray() is a clearer check for array detection

Adding and Removing Elements

Here’s a breakdown of the most important array methods for adding, removing, and rearranging elements, along with clear examples for each.

push()

Adds one or more elements to the end of an array. Returns the new array length.

let fruits = ["Apple", "Banana"];
let newLength = fruits.push("Kiwi", "Orange");
// fruits: ["Apple", "Banana", "Kiwi", "Orange"]
// newLength: 4

Use when you want to expand an array at the end.

pop()

Removes the last element from the array and returns that element.

let numbers = [1, 2, 3];
let last = numbers.pop();
// numbers: [1, 2]
// last: 3

Handy for removing the last item.

shift()

Removes the first element from the array and returns it. All remaining elements shift one position lower.

let queue = [1, 2, 3];
let first = queue.shift();
// queue: [2, 3]
// first: 1

unshift()

Adds one or more elements to the start of the array. Returns the new length.

let animals = ["Cat", "Dog"];
let len = animals.unshift("Rabbit", "Pig");
// animals: ["Rabbit", "Pig", "Cat", "Dog"]
// len: 4

splice()

Can add, remove, or replace elements at any position in the array.

Syntax:

array.splice(start, deleteCount, item1, item2, ...)

  • start: the index to change

  • deleteCount: how many elements to remove

  • item1, item2, ...: new items to add

Examples:

let colors = ["Red", "Yellow", "Blue"];
colors.splice(1, 1); // Removes "Yellow"
// colors: ["Red", "Blue"]

colors.splice(1, 0, "Green"); // Inserts "Green" at index 1
// colors: ["Red", "Green", "Blue"]

colors.splice(1, 1, "Orange"); // Replaces "Green" with "Orange"
// colors: ["Red", "Orange", "Blue"]

toSpliced()

Returns a new array with specified elements removed or replaced, leaving the original untouched (non-mutating version of splice).

let arr = ["a", "b", "c", "d"];
let newArr = arr.toSpliced(1, 2, "x", "y");
// newArr: ["a", "x", "y", "d"]
// arr: ["a", "b", "c", "d"]

slice()

Returns a new array containing a shallow copy of a portion of the original array. Does not modify the original array.

Syntax:

array.slice(start, end)

  • start: index to begin (inclusive)

  • end: index to stop (exclusive)

Example:

let nums = [0, 1, 2, 3, 4];
let part = nums.slice(1, 4); // [1, 2, 3]
Extracts subarrays for further work.

concat()

Combines two or more arrays or values, returning a new array. Original arrays aren’t changed.

let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2, 5);
// combined: [1, 2, 3, 4, 5]

copyWithin()

Copies a section of the array in place to another position within the same array.

let nums = [1, 2, 3, 4, 5];
nums.copyWithin(0, 3, 5); // Copy indexes 3–4 into start
// nums: [4, 5, 3, 4, 5]

fill()

Replaces elements in the array with a static value. Optionally use start and end to target a range.

let arr = [1, 2, 3, 4];
arr.fill(0, 2, 4); // Fills from index 2 up to (not including) 4 with 0
// arr: [1, 2, 0, 0]

with()

Returns a new array with the element at the given index replaced by a provided value, original stays unchanged (non-mutating).

let letters = ["a", "b", "c", "d"];
let updated = letters.with(2, "z");
// updated: ["a", "b", "z", "d"]
// letters: ["a", "b", "c", "d"]

Iteration and Searching

Iteration and searching array methods let you loop over elements and find specific values in a concise, declarative way.

forEach()

Executes a provided function once for each array element. Does not return a new array and can't break out early.

const numbers = [1, 2, 3];
numbers.forEach((value, index) => {
  console.log(value, index);
});
// Output:
// 1 0
// 2 1
// 3 2
This is best for side effects like logging, not transformations

map()

Creates a new array by applying a function to each element of the original array.

const nums = [1, 2, 3];
const squares = nums.map(x => x * x);
// squares: [1, 4, 9]
Original array stays the same; use for data transformation

filter()

Constructs a new array with elements that pass the test in the provided function

const nums = [1, 2, 3, 4];
const evens = nums.filter(num => num % 2 === 0);
// evens: [2, 4]
Selectively include elements that meet criteria

find()

Returns the first element matching a given condition, or undefined if none fits.

const people = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
];
const result = people.find(p => p.age > 26);
// result: { name: "Bob", age: 30 }

findIndex()

Returns the index of the first element matching the condition, or -1 if none fits.

const nums = [1, 5, 12, 8];
const idx = nums.findIndex(n => n > 10);
// idx: 2

findLast()

Returns the last element matching a test function, or undefined if not found. (Modern JS)

const arr = [4, 5, 8, 5];
const lastFive = arr.findLast(x => x === 5);
// lastFive: 5

findLastIndex()

Returns the index of the last matching element, or -1 if none fits. (Modern JS)

const arr = [4, 5, 8, 5];
const lastFiveIdx = arr.findLastIndex(x => x === 5);
// lastFiveIdx: 3

some()

Returns true if at least one array element satisfies the test function.

const nums = [1, 3, 5, 8];
const hasEven = nums.some(n => n % 2 === 0);
// hasEven: true

every()

Returns true if all array elements pass the provided test.

const nums = [2, 4, 6];
const allEven = nums.every(n => n % 2 === 0);
// allEven: true

includes()

Determines whether the array contains a certain value, using strict equality.

const letters = ["a", "b", "c"];
const hasB = letters.includes("b");
// hasB: true

indexOf()

Returns the first index at which a given value is found, or -1 if not present.

const nums = [1, 2, 3, 2];
const firstTwo = nums.indexOf(2);
// firstTwo: 1

lastIndexOf()

Returns the last index where a given value appears in the array, or -1 if not present.

const nums = [1, 2, 3, 2];
const lastTwo = nums.lastIndexOf(2);
// lastTwo: 3

entries()

Returns a new Array Iterator with [index, value] pairs for every entry.

const arr = ["x", "y"];
for (const [i, v] of arr.entries()) {
  console.log(i, v);
}
// Output:
// 0 "x"
// 1 "y"

keys()

Returns a new Array Iterator with the keys (indices) for each array element.

const fruits = ["Banana", "Orange"];
for (let key of fruits.keys()) {
  console.log(key);
}
// Output:
// 0
// 1

values()

Returns a new Array Iterator with the values for every index in the array.

const arr = ["a", "b", "c"];
for (let val of arr.values()) {
  console.log(val);
}
// Output:
// "a"
// "b"
// "c"

Sorting and Reversing

Sorting and reversing in JavaScript revolve around four core methods: sort()toSorted()reverse(), and toReversed(). These let you order arrays and flip their direction, either mutating the array or returning a new one.

sort()

Sorts the elements of an array in place and returns the same array reference.

  • By default, sorts elements as strings in ascending Unicode order.

  • For numbers or custom logic, you provide a compare function.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]

Mutates the original array.

⁠Modern engines implement sort() as stable, meaning equal elements keep their relative order.

toSorted()

Returns a new sorted array, leaving the original unchanged.
Think: “immutable sort()”.

Syntax and behavior mirror sort(), but it does not mutate:

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

const asc = nums.toSorted((a, b) => a - b);
console.log(asc);  // [1, 1, 3, 4, 5, 9]
console.log(nums); // [3, 1, 4, 1, 5, 9]

reverse()

Reverses the array in place and returns the same array reference.

const letters = ["a", "b", "c", "d"];
letters.reverse();
console.log(letters); // ["d", "c", "b", "a"]

Mutates the original array. Simple way to flip order when you do not need the original ordering anymore

toReversed()

Returns a new array with elements in reverse order, leaving the original untouched. Think: “immutable reverse()”.

const letters = ["a", "b", "c", "d"];

const reversed = letters.toReversed();
console.log(reversed); // ["d", "c", "b", "a"]
console.log(letters);  // ["a", "b", "c", "d"]

Reduction and Transformation

Reduction and transformation array methods let you turn arrays into single values, reshape nested arrays, or map-then-flatten in one step. The main ones are reduce()reduceRight()flat(), and flatMap()

reduce()

reduce() executes a reducer callback on each element (from left to right), carrying an accumulator, and returns a single final value.

Syntax:

array.reduce((accumulator, currentValue, index, array) => {
  // return new accumulator
}, initialValue);

Sum of numbers:

const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 10

Build an object:

const people = [
  { name: "Alice", city: "London" },
  { name: "Bob",   city: "Paris"  },
  { name: "Carol", city: "London" }
];

const byCity = people.reduce((acc, person) => {
  acc[person.city] ??= [];
  acc[person.city].push(person.name);
  return acc;
}, {});

// byCity: { London: ["Alice", "Carol"], Paris: ["Bob"] }

Use reduce() when you want a single result (sum, object, map, etc.) from an array.​

reduceRight()

reduceRight() works like reduce() but processes elements from right to left

Example – join paths from right side:

const segments = ["home", "user", "docs"];
const path = segments.reduceRight((acc, segment) => {
  return acc === "" ? segment : segment + "/" + acc;
}, "");
console.log(path); // "home/user/docs"
reduceRight matters when order changes the meaning (e.g., building expressions, parsing, or when data isn’t commutative).

flat()

flat() creates a new array with sub-array elements concatenated into it up to a specified depth (default depth is 1).

Basic flatten:

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

const oneLevel = nested.flat();       // [1, 2, 3, 4, [5]]
const deep     = nested.flat(2);      // [1, 2, 3, 4, 5]

Flatten completely (unknown depth):

const deeplyNested = [1, [2, [3, [4]]]];
const fullyFlat = deeplyNested.flat(Infinity); // [1, 2, 3, 4]

flatMap()

flatMap() combines map + flat(1) in one pass, returning a new array and flattening one level of nesting.

Syntax:

array.flatMap((value, index, array) => {
  // return value or array of values
});

Filter + map in one go to avoid extra empties:

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

const doubledEvens = nums.flatMap(n => 
  n % 2 === 0 ? [n * 2] : []
);
// [4, 8]

String Conversion

Array string/representation methods let you turn an array into a human‑readable string, often for display, logging, or UI. The key ones are toString(), join()toLocaleString(), and (indirectly)  valueOf().

toString()

toString() returns a comma‑separated string of the array’s elements and does not modify the original array.​

  • It internally behaves like calling join(",").

  • Empty slots behave like undefined, so you still get delimiters.

Example:

const arr = [1, 2, "a", "1a"];
console.log(arr.toString());   // "1,2,a,1a"

const sparse = [1, , 3];
console.log(sparse.toString()); // "1,,3"

Use toString() when you just need a quick, generic representation (e.g., basic logging).

join()

join(separator?) returns a string with all elements joined using the given separator; default is a comma.​

  • Does not mutate the original array.

  • Lets you control the delimiter, which is the main advantage over toString().

Examples:

const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.join());        // "Apple,Banana,Mango"
console.log(fruits.join(" | "));   // "Apple | Banana | Mango"
console.log(fruits.join(""));      // "AppleBananaMango"

toLocaleString()

toLocaleString(locales?, options?) returns a string where each element is converted using its own toLocaleString() and joined with a locale‑specific separator.​

  • Great for arrays of numbers, dates, or currencies that must respect user locale.

  • Separator and formatting depend on locales and options.

Basic example:

const mixed = [1000, new Date("2024-01-15"), 3.14159];

const result = mixed.toLocaleString(); 
// e.g. in en-US: "1,000,1/15/2024, 12:00:00 AM,3.142"

valueOf()

For arrays, valueOf() just returns the array itself, so you rarely call it directly.​

Example:

const arr = [1, 2, 3];
console.log(arr.valueOf() === arr); // true

It’s mainly used implicitly by JavaScript when coercing objects, but for string representation you will almost always use  toString()join(), or toLocaleString() instead.

Copying and Cloning

Copying and cloning arrays in modern JavaScript is usually done with patterns like spread ([...]), Array.from(), slice(), and structuredClone(). These matter because many array methods mutate, so safe copies are essential for predictable code.

Shallow copies (1 level deep)

Spread syntax [...array]

Creates a shallow copy: top‑level elements are copied, nested objects/arrays are still shared.

const original = [1, 2, 3];
const copy = [...original];

copy.push(4);

console.log(original); // [1, 2, 3]
console.log(copy);     // [1, 2, 3, 4]

With objects:

const arr = [{ a: 1 }, { a: 2 }];
const copy = [...arr];

copy[0].a = 99;
console.log(arr[0].a); // 99 (same object reference)

Array.from()

Also makes a shallow copy, but works on any iterable/array‑like and can map while copying.

const original = [1, 2, 3];
const copy = Array.from(original);

const doubled = Array.from(original, x => x * 2);
// original: [1, 2, 3]
// doubled:  [2, 4, 6]

Useful when:

  • You get arguments, NodeList, or a Set.

  • You want transform + copy together.

slice() with no args

slice() with no parameters returns a shallow copy of the entire array.

const nums = [1, 2, 3];
const copy = nums.slice();

copy[0] = 99;
console.log(nums); // [1, 2, 3]
console.log(copy); // [99, 2, 3]

Deep copies (including nested structures)

structuredClone()

structuredClone(value) creates a deep clone of supported data: arrays, objects, Maps, Sets, Dates, RegExps, and more.

const original = [
  { name: "Alice", scores: [10, 20] },
  { name: "Bob",   scores: [30, 40] }
];

const clone = structuredClone(original);

clone[0].scores[0] = 999;

console.log(original[0].scores[0]); // 10 (unchanged)
console.log(clone[0].scores[0]);    // 999

Notes:

  • Functions, DOM nodes, and some other types are not cloned.

  • Safer and clearer than JSON.parse(JSON.stringify(...)) and preserves more types.

When to use which

  • Need a simple, shallow copy of an array:

    • const copy = [...arr];

    • or const copy = arr.slice();

  • Need to copy an iterable / array‑like and possibly map:

    • const copy = Array.from(iterable, mapFn);

  • Need a full deep clone including nested arrays/objects:

    • const deepCopy = structuredClone(arr);

JavaScript

    React

      NextJS

        HTML

          CSS

            Sign up for our newsletter.

            Copyright © theHardCoder 2021 - 2025