• JavaScript Video Tutorials

JavaScript - Array with() Method



In JavaScript, the Array.with() method is used to update a specific element in an array. It takes two parameters: "index," which is the index of the element to be updated, and "value," which is the new value to be assigned at the given index. This method does not change the original array; instead, it returns a new array that contains the updated elements.

The Array.with() method is added by ES2023 as a safe and secure way to modify array elements without altering the original array.

Syntax

Following is the syntax of JavaScript Array.with() method −

arrayInstance.with(index, value)

Parameters

This method accepts two parameters. The same is described below −

  • index − An index position at which the value will be replaced.
    • If we provide a negative index, it counts from the end of the array.
    • If the provided index is out of bound, a RangeError will be thrown.
  • value − The value to be assigned at the given index.

Return value

This method returns a new array with the element at index replaced with value.

Examples

Example 1

In the following example, we are replacing the element at index 2 with the provided value "Tutorialspoint" using the JavaScript Array.with() method.

<html>
<body>
   <script>
      let numbers = [11, 22, 44, 55];
      let result = numbers.with(2, "Tutorialspoint");
      document.write(result);
   </script>
</body>
</html>

Output

11,22,Tutorialspoint,55

Example 2

In this example, we are first updating the value at index 2 with element '6' and then we are multiplying each element in the updated array by '2'.

<html>
<body>
   <script>
      let numbers = [2, 3, 4, 5];
      let result = numbers.with(2, 6).map((x) => x*2);
      document.write(result);
   </script>
</body>
</html>

Output

4,6,12,10

Example 3

In the example below, we are using the with() method on sparse array.

<html>
<body>
   <script>
      let numbers = [2, , 4, , 6];
      let result = numbers.with(3, "Tutorix"); // [2, undefined, 4, Tutorix, 6]
      document.write(result);
   </script>
</body>
</html>

Output

As we can see in the output, the empty value in index 3 is replaced with "Tutorix".

2,,4,Tutorix,6

Example 4

A "RangeError" is thrown if the (index is greater than or equal to the length of the array) or if the (index is less than the negative length of the array).

<html>
<body>
   <script>
      let numbers = [2, 3, 4, 5, 6];
      try {
         numbers.with(10, "Tutorix");
      } catch (error) {
         document.write(error);
      }
   </script>
</body>
</html>

If we execute the above program, it will give a "RangeError" because we have provided an index number that is greater than the array length.

Output

RangeError: Invalid index : 10
Advertisements