JavaScript TypedArray.prototype.with() Method
A new method TypedArray.prototype.with(), was introduced in ECMAScript 2023 (ES2023) to provide a means of modifying an element in a particular TypedArray without altering the underlying array directly, it generates a new TypedArray with the required alteration and then returns it.
TypedArray instances with() method copies to changing a value at a particular index through bracket notation, giving back a fresh typed array where the value at the specified index is substituted with the specified one, Array.prototype.with() employs an equivalent procedure.
Syntax
TypedArray.prototype.with(index, value)
Parameter:
- index: (Required) Zero-based index at which to change the typed array, converted to an integer.
- value: (Required) Any value to be assigned to the given index.
Return Type:
A new typed array with the element index
replaced with value
.
Example 1: In this example, we are replacing an element.
const numbers = new Int8Array([1, 3, 5, 7, 9]);
const modifiedNumbers = numbers.with(2, 10);
console.log(numbers);
console.log(modifiedNumbers);
Output:
Int8Array(5) [1, 3, 5, 7, 9]
Int8Array(5) [1, 3, 10, 7, 9]
Example 2: In this example, we are chaining with other methods.
// Red, Green, Blue color values
const colors = new Uint8Array([255, 0, 0, 0, 255, 0]);
const modifiedColors = colors.with(1, 255).with(5, 255);
// Output: Uint8Array(6) [255, 0, 0, 0, 255, 0]
// (original remains unchanged)
console.log(colors);
// Output: Uint8Array(6) [255, 255, 0, 0, 255, 255]
// (both green and blue set to 255)
console.log(modifiedColors);
Output:
Uint8Array(6) [255, 0, 0, 0, 255, 0]
Uint8Array(6) [255, 255, 0, 0, 255, 255]
Supported Browsers
- Chrome
- Edge
- Firefox
- Opera
- Safari