JavaScript Array with() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Immutable replace

What You’ll Learn

The with() method returns a new array with one element replaced at a given index. The original stays unchanged. This tutorial covers syntax, negative indexes, comparison with bracket assignment, the ES2023 immutable methods family, and five examples.

01

Syntax

with(i, val)

02

New array

Non-mutating

03

Negative i

From end

04

RangeError

Bad index

05

vs arr[i]=

Immutable

06

ES2023

Modern

Introduction

Updating one slot in an array usually means arr[2] = "new", which mutates the original. In React and other immutable workflows, you need a copy with one change instead. with(index, value) does exactly that in one readable call.

It is part of the ES2023 “change by copy” family alongside toReversed(), toSorted(), and toSpliced().

Understanding the with() Method

array.with(index, value) shallow-copies the array, sets the resolved index to value, and returns the new array. Length stays the same; no elements are added or removed.

If the index is out of range after resolving negatives, a RangeError is thrown. Unlike at(), which returns undefined for bad reads, with() refuses invalid writes.

💡
Beginner Tip

Always assign the result: const updated = arr.with(1, "x"). Calling arr.with(1, "x") alone without using the return value leaves arr unchanged—which is correct, but easy to forget.

📝 Syntax

General form of Array.prototype.with:

JavaScript
array.with(index, value)

Parameters

  • index — position to replace (negative counts from end).
  • value — new element at that index.

Return value

  • A new array with one element replaced.

Common patterns

  • arr.with(0, "first") — replace start.
  • arr.with(-1, "last") — replace end.
  • setState(arr.with(i, val)) — React immutable update.
  • [...arr.slice(0,i), val, ...arr.slice(i+1)] — classic fallback.

⚡ Quick Reference

GoalCode
Replace at indexarr.with(i, val)
Replace lastarr.with(-1, val)
Mutate in placearr[i] = val
Invalid indexThrows RangeError
ES2023 siblingstoReversed, toSorted, toSpliced
Mutates original?No

📋 with() vs arr[i] = vs splice vs map

Pick immutable single-slot replace vs mutate vs multi-edit.

with
one slot

New array

arr[i] =
in place

Mutates

splice
add/remove

Mutates

map
all slots

Transform

Examples Gallery

Open DevTools Console (F12) or use Try-it labs. Example N maps to ?tryit=N. Requires a browser with ES2023 with() support.

📚 Getting Started

Replace one element and keep the original intact.

Example 1 — Replace an Element at an Index

Swap index 2 for "pineapple".

JavaScript
const fruits = ["apple", "orange", "banana", "grape"];

const updated = fruits.with(2, "pineapple");

console.log(updated);
// ["apple", "orange", "pineapple", "grape"]

console.log(fruits[2]);
// "banana"
Try It Yourself

How It Works

Only index 2 changes in the new array. fruits still holds "banana" at that position.

Example 2 — Original Array Stays Unchanged

Compare references and contents after with().

JavaScript
const original = [1, 2, 3, 4, 5];
const modified = original.with(2, 999);

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

console.log(modified);
// [1, 2, 999, 4, 5]

console.log(original === modified);
// false
Try It Yourself

How It Works

with() always produces a new array reference. Shallow copy: nested objects are still shared.

📈 Practical Patterns

Negative index, mutation contrast, and error handling.

Example 3 — Replace the Last Element (-1)

Negative index counts from the end.

JavaScript
const items = ["a", "b", "c"];

const updated = items.with(-1, "z");

console.log(updated);
// ["a", "b", "z"]
Try It Yourself

How It Works

-1 resolves to index 2 (last item). Same negative-index rules as at().

Example 4 — with() vs arr[i] =

Side-by-side immutable vs mutating update.

JavaScript
const immutable = [10, 20, 30];
const mutable = [10, 20, 30];

const next = immutable.with(1, 99);
mutable[1] = 99;

console.log("immutable original:", immutable);
// [10, 20, 30]

console.log("with result:", next);
// [10, 99, 30]

console.log("mutable after [1]=:", mutable);
// [10, 99, 30]
Try It Yourself

How It Works

Both produce [10, 99, 30] in the result you use—but only with() preserves the first array for history, undo, or React diffing.

Example 5 — Out-of-Range Index Throws RangeError

Index 10 does not exist in a length-4 array.

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

try {
  nums.with(10, 0);
} catch (err) {
  console.log(err.name);
  // "RangeError"
}
Try It Yourself

How It Works

with() cannot grow the array. To append, use push, spread, or concat instead.

🚀 Common Use Cases

  • React statesetItems(items.with(i, newVal)).
  • Undo stacks — keep prior array version intact.
  • Immutable configs — tweak one setting in a list.
  • Game boards — update one cell in a grid array.
  • Form rows — replace one field value in an array of inputs.
  • Functional style — chain with other non-mutating methods.

🧠 How with() Runs

1

Resolve index

Negative? Count from length.

Validate
2

Shallow copy

New array, same length.

Copy
3

Set one slot

Replace value at index.

Replace
4

Return new array

Original untouched.

📝 Notes

  • Does not mutate the original array.
  • Returns a new array (assign the result).
  • Shallow copy—nested objects are shared.
  • Invalid index throws RangeError.
  • Does not change array length.
  • ES2023—use spread/slice fallback for older browsers.
  • Not the same as JavaScript’s deprecated with statement.

Browser & Runtime Support

Array.prototype.with() was added in ES2023 as part of the immutable array methods proposal (toReversed, toSorted, toSpliced, with).

Baseline · ES2023

Array.prototype.with()

Supported in Chrome 110+, Firefox 115+, Safari 16+, Edge 110+, and Node.js 20+. Not available in Internet Explorer or very old browsers.

92% Modern browsers
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
Array.with() Good

Bottom line: Use spread + slice for older targets: [...arr.slice(0, i), val, ...arr.slice(i + 1)].

Conclusion

with() is the clean, immutable way to replace one array element by index. It pairs with other ES2023 copy methods and fits modern state management where originals must stay unchanged.

You have reached the last instance method in this series—return to the array methods overview to review the full toolkit.

💡 Best Practices

✅ Do

  • Assign the returned new array
  • Use in React/Redux immutable updates
  • Use negative index for last-element edits
  • Wrap in try/catch if index may be invalid
  • Combine with other ES2023 copy methods

❌ Don’t

  • Forget to capture the return value
  • Use with() to append (length stays same)
  • Assume deep clone of nested objects
  • Confuse with the old with statement
  • Expect it in IE without polyfill

Key Takeaways

Knowledge Unlocked

Five things to remember about Array.with()

Immutable single-index replacement.

5
Core concepts
📋 02

New array

Non-mutating.

Copy
03

Negative i

From end.

Index
04

RangeError

Bad index.

Edge
🔄 05

ES2023

Change-by-copy.

Modern

❓ Frequently Asked Questions

with(index, value) returns a new array with the element at index replaced by value. The original array is not modified.
No. with() always returns a new array. Assign the result to use the updated copy: const next = arr.with(2, 'new').
Yes. Negative index counts from the end, like at(). with(-1, value) replaces the last element.
with() throws a RangeError if the resolved index is less than 0 or greater than or equal to array.length. It does not extend the array.
Bracket assignment mutates the original array in place. with() returns a new array and leaves the original unchanged—ideal for React state and immutable patterns.
with() is ES2023 (2023). It works in Chrome 110+, Firefox 115+, Safari 16+, Edge 110+, and Node.js 20+. Use spread/slice fallback for older environments.
Did you know?

JavaScript once had a with statement (now forbidden in strict mode). Array.prototype.with() is unrelated—it is a safe, modern method name for immutable index replacement.

Back to Array methods hub

Review the full list of instance methods you have learned in this series.

Array methods overview →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful