JavaScript Tutorials

JavaScript Array with()
Syntax & Examples

Array.with() method

The with() method of the Array class in JavaScript returns a new array with the element at the given index replaced with the given value, without modifying the original array.


Syntax of Array.with()

The syntax of Array.with() method is:

arrayInstance.with(index, value)

This with() method of Array returns a new array with the element at the given index replaced with the given value, without modifying the original array.

Parameters

ParameterOptional/RequiredDescription
indexrequiredThe index of the element to replace.
valuerequiredThe value to replace at the specified index.

Return Type

Array.with() returns value of type Array.



✐ Examples

1 Using with() method to replace an element at a specific index

In JavaScript, we can use the with() method to replace an element at a specific index in an array.

For example,

  1. We define an array variable arr with elements [1, 2, 3, 4, 5].
  2. We use the with() method on arr to replace the element at index 2 with the value 10.
  3. A new array is returned with the element at index 2 replaced with 10.
  4. We log the new array to the console using console.log() method to see the replaced element.

JavaScript Program

const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 10);
console.log(newArr);

Output

[1, 2, 10, 4, 5]

2 Using with() method to replace an element at a specific index

In JavaScript, we can use the with() method to replace an element at a specific index in an array.

For example,

  1. We define an array variable arr with elements ['apple', 'banana', 'cherry', 'date'].
  2. We use the with() method on arr to replace the element at index 1 with the value 'orange'.
  3. A new array is returned with the element at index 1 replaced with 'orange'.
  4. We log the new array to the console using console.log() method to see the replaced element.

JavaScript Program

const arr = ['apple', 'banana', 'cherry', 'date'];
const newArr = arr.with(1, 'orange');
console.log(newArr);

Output

['apple', 'orange', 'cherry', 'date']

Summary

In this JavaScript tutorial, we learned about with() method of Array: the syntax and few working examples with output and detailed explanation for each example.