JavaScript Array Methods: Complete Guide (Mutating vs Non-Mutating)
JavaScript arrays have more than 30 built-in methods. The single most important thing to know about each one is whether it changes the original array (mutates it) or returns a new one. Getting that wrong causes some of the most confusing bugs in test code, such as shared test data that silently changes between tests. In this lesson you will learn the essential array methods grouped by what they do, with the modern non-mutating versions added in ES2023.
📖 What You’ll Learn: mutating versus non-mutating methods, splice for inserting, removing and replacing, slice for copying parts, concat and spread, join and toString, includes, indexOf and lastIndexOf, reverse and toReversed, fill, flat and flatMap, toSorted, toSpliced and with, Array.isArray, Array.from and Array.of, and a cheat sheet.
⚠️ Mutating vs Non-Mutating Methods
Definition: a mutating method changes the array it is called on. A non-mutating method leaves the original untouched and returns a new value (often a new array).
| Mutating (change the array) | Non-mutating (return something new) |
|---|---|
push, pop, shift, unshift | slice, concat, join |
splice | toSpliced (ES2023) |
sort | toSorted (ES2023) |
reverse | toReversed (ES2023) |
fill, copyWithin | with (ES2023) |
Assigning arr[i] = x | map, filter, flat, flatMap, includes, indexOf, find… |
📄 mutating.js
const original = [3, 1, 2];
const sortedCopy = original.toSorted(); // new array
console.log(original, sortedCopy);
const sameArray = original.sort(); // sorts in place AND returns the same array
console.log(original, sameArray === original);
⌨️ Terminal
node mutating.js
🖥️ Output
[ 3, 1, 2 ] [ 1, 2, 3 ]
[ 1, 2, 3 ] true
⚠️ Watch out: Test data defined once at the top of a file and then sorted, reversed or spliced by one test is changed for every later test. Use the non-mutating versions (or copy first with [...arr]) on shared data.
✂️ splice: Insert, Remove and Replace (Mutating)
arr.splice(start, deleteCount, ...itemsToInsert) changes the array in place and returns the removed items.
📄 splice.js
const steps = ["open", "login", "search", "logout"];
const removed = steps.splice(2, 1); // remove 1 item at index 2
console.log(removed, steps);
steps.splice(2, 0, "add to cart", "checkout"); // insert without removing
console.log(steps);
steps.splice(1, 1, "login with SSO"); // replace 1 item
console.log(steps);
steps.splice(-1); // remove from index -1 to the end
console.log(steps);
⌨️ Terminal
node splice.js
🖥️ Output
[ 'search' ] [ 'open', 'login', 'logout' ]
[ 'open', 'login', 'add to cart', 'checkout', 'logout' ]
[ 'open', 'login with SSO', 'add to cart', 'checkout', 'logout' ]
[ 'open', 'login with SSO', 'add to cart', 'checkout' ]
Removing an item by value is a common job: find its index first, and only splice if it was found.
📄 remove-by-value.js
const tags = ["smoke", "flaky", "api"];
const i = tags.indexOf("flaky");
if (i !== -1) tags.splice(i, 1);
console.log(tags);
const j = tags.indexOf("missing");
tags.splice(j, 1); // bug: j is -1, so this removes the LAST item
console.log(tags);
⌨️ Terminal
node remove-by-value.js
🖥️ Output
[ 'smoke', 'api' ]
[ 'smoke' ]
💡 Tip: arr.toSpliced(start, deleteCount, ...items) (ES2023) does the same as splice but returns a new array and leaves the original alone. To remove by value without mutating, arr.filter((x) => x !== value) is the simplest choice.
📎 slice: Copy Part of an Array (Non-Mutating)
arr.slice(start, end) returns a new array with the items from start up to, but not including, end. Negative indexes count from the end. It works exactly like String.prototype.slice.
📄 slice.js
const runs = ["run1", "run2", "run3", "run4", "run5"];
console.log(runs.slice(1, 3)); // index 1 and 2
console.log(runs.slice(2)); // from index 2 to the end
console.log(runs.slice(-2)); // last two
console.log(runs.slice()); // full shallow copy
console.log(runs); // unchanged
⌨️ Terminal
node slice.js
🖥️ Output
[ 'run2', 'run3' ]
[ 'run3', 'run4', 'run5' ]
[ 'run4', 'run5' ]
[ 'run1', 'run2', 'run3', 'run4', 'run5' ]
[ 'run1', 'run2', 'run3', 'run4', 'run5' ]
slice(start, end) | splice(start, count, ...items) | |
|---|---|---|
| Changes the original? | No | Yes |
| Second argument | End index (exclusive) | Number of items to remove |
| Returns | A new array of the selected items | An array of the removed items |
🔗 concat, Spread, join and toString
📄 concat-join.js
const smoke = ["login", "search"];
const regression = ["refund", "export"];
console.log(smoke.concat(regression, ["extra"])); // new array
console.log([...smoke, ...regression]); // same with spread
console.log(smoke.join(" > ")); // array -> string
console.log(smoke.join(""), "|", smoke.toString());
console.log([1, [2, [3]]].join("-")); // nested arrays are stringified
console.log([null, undefined, 0].join(",")); // null/undefined become empty
⌨️ Terminal
node concat-join.js
🖥️ Output
[ 'login', 'search', 'refund', 'export', 'extra' ]
[ 'login', 'search', 'refund', 'export' ]
login > search
loginsearch | login,search
1-2,3
,,0
🔍 includes, indexOf and lastIndexOf
📄 search.js
const codes = [200, 201, 404, 500, 404];
console.log(codes.includes(404), codes.includes(302));
console.log(codes.indexOf(404), codes.lastIndexOf(404), codes.indexOf(302));
console.log(codes.includes(500, 4)); // search from index 4
console.log([NaN].includes(NaN), [NaN].indexOf(NaN)); // includes handles NaN
console.log([{ id: 1 }].includes({ id: 1 })); // objects compare by reference
⌨️ Terminal
node search.js
🖥️ Output
true false
2 4 -1
false
true -1
false
includesanswers “is it there?” and returns a boolean; it also findsNaN.indexOfreturns the position or-1; use it when you need the index.- Both use strict equality, so they cannot find an object by its contents. Use
find/somewith a callback for that (lesson 30).
🔃 reverse, toReversed, fill and with
📄 reverse-fill.js
const order = ["first", "second", "third"];
console.log(order.toReversed(), order); // new reversed array, original kept
order.reverse(); // in place
console.log(order);
console.log(new Array(4).fill("pending"));
const grid = [0, 0, 0, 0, 0];
grid.fill(1, 1, 3); // fill indexes 1 and 2
console.log(grid);
const statuses = ["ok", "ok", "ok"];
console.log(statuses.with(1, "fail"), statuses); // replace one item in a copy
⌨️ Terminal
node reverse-fill.js
🖥️ Output
[ 'third', 'second', 'first' ] [ 'first', 'second', 'third' ]
[ 'third', 'second', 'first' ]
[ 'pending', 'pending', 'pending', 'pending' ]
[ 0, 1, 1, 0, 0 ]
[ 'ok', 'fail', 'ok' ] [ 'ok', 'ok', 'ok' ]
⚠️ Watch out: Never fill an array with the same object if you plan to change items: new Array(3).fill({}) puts the same object in every slot. Use Array.from({ length: 3 }, () => ({})) to create separate objects.
📄 fill-trap.js
const shared = new Array(2).fill({ count: 0 });
shared[0].count++;
console.log(shared);
const separate = Array.from({ length: 2 }, () => ({ count: 0 }));
separate[0].count++;
console.log(separate);
⌨️ Terminal
node fill-trap.js
🖥️ Output
[ { count: 1 }, { count: 1 } ]
[ { count: 1 }, { count: 0 } ]
🪜 flat and flatMap
flat(depth = 1) returns a new array with nested arrays merged into it up to the given depth. flatMap(fn) maps each item to an array and flattens the result by one level.
📄 flat.js
const suites = [["login", "logout"], ["cart", ["add", "remove"]]];
console.log(suites.flat()); // one level
console.log(suites.flat(Infinity)); // all levels
const tests = [
{ name: "login", tags: ["smoke", "auth"] },
{ name: "cart", tags: ["regression"] },
];
console.log(tests.flatMap((t) => t.tags)); // all tags
console.log(tests.flatMap((t) => t.tags.map((tag) => `${t.name}:${tag}`)));
console.log([1, 2, 3].flatMap((n) => (n % 2 ? [n, n] : []))); // duplicate odd, drop even
⌨️ Terminal
node flat.js
🖥️ Output
[ 'login', 'logout', 'cart', [ 'add', 'remove' ] ]
[ 'login', 'logout', 'cart', 'add', 'remove' ]
[ 'smoke', 'auth', 'regression' ]
[ 'login:smoke', 'login:auth', 'cart:regression' ]
[ 1, 1, 3, 3 ]
🧰 Static Methods: Array.isArray, Array.from, Array.of
📄 static.js
console.log(Array.isArray([]), Array.isArray("abc"), Array.isArray({ length: 0 }));
console.log(Array.from("abc")); // iterable -> array
console.log(Array.from({ length: 3 }, (_, i) => `user${i + 1}`));
console.log(Array.from(new Map([["a", 1]]))); // Map -> [[key, value]]
console.log(Array.from([1, 2, 3], (n) => n * 10)); // with a mapping function
console.log(Array.of(5), Array.of(1, 2));
⌨️ Terminal
node static.js
🖥️ Output
true false false
[ 'a', 'b', 'c' ]
[ 'user1', 'user2', 'user3' ]
[ [ 'a', 1 ] ]
[ 10, 20, 30 ]
[ 5 ] [ 1, 2 ]
In Node.js tests you often get iterables (Sets, Maps, matchAll results). Array.from(...) or [...iterable] turns them into arrays so every array method becomes available.
📋 Array Methods Cheat Sheet
| Goal | Method | Mutates? |
|---|---|---|
| Add / remove at end | push / pop | Yes |
| Add / remove at start | unshift / shift | Yes |
| Insert / remove / replace in the middle | splice (or toSpliced) | Yes (No) |
| Copy part | slice | No |
| Join arrays | concat, [...a, ...b] | No |
| Array to text | join | No |
| Is the value there? Where? | includes, indexOf, lastIndexOf | No |
| Reverse | reverse (or toReversed) | Yes (No) |
| Sort | sort (or toSorted) | Yes (No) |
| Replace one item | arr[i] = x (or with) | Yes (No) |
| Flatten nested arrays | flat, flatMap | No |
| Transform / select / combine | map, filter, reduce (next lesson) | No |
🧪 Tester Scenario: Keep Shared Test Data Safe
A test file defines a list of users once. Two “tests” each need a modified version. Mutating methods break the second test; non-mutating methods keep both correct:
📄 shared-data.js
const USERS = ["admin", "editor", "viewer"];
// Bad: mutating the shared array
function testRemoveViewerBad(users) {
users.splice(users.indexOf("viewer"), 1);
return users.length === 2;
}
function testHasThreeRoles(users) {
return users.length === 3;
}
const shared = [...USERS];
console.log("bad:", testRemoveViewerBad(shared), testHasThreeRoles(shared));
// Good: non-mutating versions
function testRemoveViewerGood(users) {
const withoutViewer = users.filter((u) => u !== "viewer");
return withoutViewer.length === 2;
}
console.log("good:", testRemoveViewerGood(USERS), testHasThreeRoles(USERS));
console.log("reversed view:", USERS.toReversed(), "original:", USERS);
⌨️ Terminal
node shared-data.js
🖥️ Output
bad: true false
good: true true
reversed view: [ 'viewer', 'editor', 'admin' ] original: [ 'admin', 'editor', 'viewer' ]
💡 Tip: Object.freeze(USERS) makes accidental mutation throw an error in strict mode, which turns this kind of hidden bug into an immediate failure.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Remove "b" and "c" from ["a", "b", "c", "d"] with one splice call and print the removed items and the array.
Show answer
📄 practice1.js
const letters = ["a", "b", "c", "d"];
const removed = letters.splice(1, 2);
console.log(removed, letters);🖥️ Output
[ 'b', 'c' ] [ 'a', 'd' ]Q2. Insert "verify email" between "register" and "login" in ["register", "login", "logout"] without changing the original array.
Show answer
📄 practice2.js
const steps = ["register", "login", "logout"];
const updated = steps.toSpliced(1, 0, "verify email");
console.log(updated, steps);🖥️ Output
[ 'register', 'verify email', 'login', 'logout' ] [ 'register', 'login', 'logout' ]Q3. Get the middle three items of [10, 20, 30, 40, 50] with slice.
Show answer
📄 practice3.js
const values = [10, 20, 30, 40, 50];
console.log(values.slice(1, 4));🖥️ Output
[ 20, 30, 40 ]Q4. Turn ["2026", "11", "23"] into the string "2026-11-23" and back into an array.
Show answer
📄 practice4.js
const parts = ["2026", "11", "23"];
const date = parts.join("-");
console.log(date, date.split("-"));🖥️ Output
2026-11-23 [ '2026', '11', '23' ]Q5. From [{ suite: "a", tests: ["t1", "t2"] }, { suite: "b", tests: ["t3"] }], produce a flat list of all test names with flatMap.
Show answer
📄 practice5.js
const suites = [{ suite: "a", tests: ["t1", "t2"] }, { suite: "b", tests: ["t3"] }];
console.log(suites.flatMap((s) => s.tests));🖥️ Output
[ 't1', 't2', 't3' ]Q6. Write removeValue(arr, value) that returns a new array without any occurrence of value, and leaves the input unchanged.
Show answer
📄 practice6.js
const removeValue = (arr, value) => arr.filter((x) => x !== value);
const tags = ["smoke", "flaky", "api", "flaky"];
console.log(removeValue(tags, "flaky"), tags);🖥️ Output
[ 'smoke', 'api' ] [ 'smoke', 'flaky', 'api', 'flaky' ]🧠 MCQ Quiz: Array Methods
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which method does NOT change the original array?Answer: slice. slice returns a new array.
- What does
splicereturn?Answer: An array of the removed items. The original array is changed in place. - What is
[1, 2, 3, 4].slice(1, 3)?Answer: [2, 3]. End index 3 is not included. - What does
arr.splice(-1, 1)do?Answer: Removes the last item. Negative start counts from the end; this is why splice(indexOf(x), 1) with -1 is a bug. - Which ES2023 method sorts without mutating?Answer: toSorted. toReversed, toSpliced and with were added at the same time.
- What is
[[1, 2], [3, [4]]].flat()?Answer: [1, 2, 3, [4]]. flat() flattens one level by default. - What does
[NaN].includes(NaN)return?Answer: true. includes uses SameValueZero, which treats NaN as equal; indexOf does not. - What is wrong with
new Array(3).fill({})?Answer: All slots hold the same object. Use Array.from({ length: 3 }, () => ({})). - What does
["a", "b"].join("")return?Answer: “ab”. The separator is an empty string. - What does
[5, 1].sort() === originaltell you?Answer: sort returns the same (mutated) array. sort sorts in place and returns the same reference.
💼 Interview Questions and Answers
Q1. What is the difference between slice and splice?
slice(start, end) is non-mutating: it returns a shallow copy of a portion, with end exclusive. splice(start, deleteCount, ...items) mutates the array: it removes and/or inserts items in place and returns the removed items. Since ES2023, toSpliced provides a non-mutating version of splice.
Q2. Which array methods mutate the original array?
push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin, plus direct assignment (arr[i] = x, arr.length = 0). Everything else, including map, filter, slice, concat, flat and the ES2023 methods toSorted, toReversed, toSpliced and with, returns a new value.
Q3. How do you remove duplicates from an array?
📄 dedupe.js
const tags = ["smoke", "api", "smoke", "ui", "api"];
console.log([...new Set(tags)]);
console.log(tags.filter((t, i) => tags.indexOf(t) === i));
const users = [{ id: 1 }, { id: 2 }, { id: 1 }];
console.log([...new Map(users.map((u) => [u.id, u])).values()]);
⌨️ Terminal
node dedupe.js
🖥️ Output
[ 'smoke', 'api', 'ui' ]
[ 'smoke', 'api', 'ui' ]
[ { id: 1 }, { id: 2 } ]
A Set is simplest for primitives. For objects, deduplicate by a key, for example with a Map keyed by id.
Q4. What is the difference between flat and flatMap?
flat(depth) only flattens nested arrays (default depth 1, Infinity for all levels). flatMap(fn) first maps each element with fn and then flattens the result by exactly one level; it is equivalent to map(fn).flat() but more efficient, and returning an empty array from fn removes the element.
❓ Frequently Asked Questions
🤔 How do I empty an array in JavaScript?
Set arr.length = 0 or call arr.splice(0) to empty the same array, or assign a new empty array (arr = []) if the variable is let and nothing else holds a reference.
🤔 How do I add an item to the start of an array without mutating it?
Use spread: [newItem, ...arr]. To add at the end: [...arr, newItem].
🤔 Are toSorted and toReversed safe to use?
Yes. They are part of ES2023 and supported by Node.js 20+ and all current browsers.
🤔 What is the difference between includes and some?
includes(value) checks for an exact value with strict equality. some(fn) runs a test function, so it can match objects by their properties.
🏁 Summary
- Know which methods mutate:
push/pop/shift/unshift/splice/sort/reverse/fillchange the array. spliceinserts, removes and replaces in place;slicecopies part of an array.concat/spread join arrays;jointurns them into text;includes/indexOfsearch for values.flatandflatMapflatten nested arrays.- ES2023
toSorted,toReversed,toSplicedandwithreturn new arrays, ideal for shared test data.
Next, continue with Lesson 30: map, filter and reduce. For extra practice, solve the JavaScript array practice programs.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in