JavaScript slice() and concat() - Extract and Merge Arrays

Master Array.slice() for extracting sub-arrays and concat() for merging arrays immutably. Covers shallow copying, pagination, and spread operator alternatives. Free reference.

Extraction

Detailed Explanation

Understanding slice() and concat()

Both methods are non-mutating — they always return new arrays, leaving the originals intact.

Array.slice()

Extracts a section of an array:

const arr = ["a", "b", "c", "d", "e"];

arr.slice(1, 3);   // ["b", "c"]     (start inclusive, end exclusive)
arr.slice(2);      // ["c", "d", "e"] (from index 2 to end)
arr.slice(-2);     // ["d", "e"]      (last 2 elements)
arr.slice();       // ["a", "b", "c", "d", "e"] (shallow clone)

Shallow Copy Behavior

slice() creates a shallow copy. Nested objects still share references:

const original = [{ x: 1 }, { x: 2 }];
const copy = original.slice();
copy[0].x = 99;
console.log(original[0].x); // 99 — same object!

For deep copies, use structuredClone().

Pagination with slice

function getPage(items, page, pageSize) {
  const start = (page - 1) * pageSize;
  return items.slice(start, start + pageSize);
}
getPage(["a","b","c","d","e","f"], 2, 2); // ["c", "d"]

Array.concat()

Merges arrays and/or values into a new array:

const a = [1, 2];
const b = [3, 4];
a.concat(b);        // [1, 2, 3, 4]
a.concat(3, [4, 5]); // [1, 2, 3, 4, 5]

concat flattens arrays by one level but does NOT deep-flatten:

[1].concat([2, [3, 4]]); // [1, 2, [3, 4]]

Spread Operator Alternative

The spread operator is often preferred over concat:

// concat equivalent
const merged = [...a, ...b];

// Prepend/append
const withNew = [...existingItems, newItem];
const withFirst = [firstItem, ...existingItems];

Both spread and concat have O(n+m) complexity, where n and m are the array lengths.

Use Case

Use slice() for pagination, extracting sub-arrays, creating shallow copies before sorting or reversing, and getting the last N elements. Use concat() or the spread operator for merging data from multiple sources without modifying the originals.

Try It — JavaScript Array Methods Reference

Open full tool