JavaScript Array withMethod

Array 对象参考手册JavaScript Array Object

ES2023 introduced the Array with() method, which is a safe way to update array elements without modifying the original array.

Example

Change the value of the second element of the array:

const sites = ["Google", "Baidu", "Example", "Taobao"]; const site = sites.with(1, "JYSHARE");

siteOutput:

Google,JYSHARE,Example,Taobao

Try it yourself »

Definition and Usage

The with() method is used to update the specified array element.

The with() method returns a new array.

The with() method does not change the original array.


Browser Support

with() is an ES2023 feature.

As of July 2023, all modern browsers support this feature:

Chrome 110 Edge 110 Firefox 115 Safari 16.4 Opera 96
Feb 2023 Feb 2023 Jul 2023 Mar 2023 May 2023

Syntax

array.with(index, value)

Parameters

Parameter Description
index Required. The index (position) of the element to be changed. Negative indexes count from the end of the array.
value Required. The new value.

Return Value

Type Description
Array Object Returns a new array containing the changed element.


Array 对象参考手册JavaScript Array Object

Other Extensions