Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

JavaScript Array with() Method

Posted on December 31, 2024December 31, 2024 By Admin No Comments on JavaScript Array with() Method

The Array.with() method is a modern JavaScript feature introduced in ECMAScript 2023 (ES14). It creates a shallow copy of an array and replaces the element at a specified index with a new value, leaving the original array unchanged. This makes it a non-mutating alternative for modifying elements in an array.

Syntax

let newArray = arr.with(index, value);

Parameters

ParameterDescription
index(Required) The index of the element to replace. Can be positive or negative.
value(Required) The new value to set at the specified index.

Return Value

The method returns a new array with the specified index replaced by the provided value. If the index is out of range, the method throws a RangeError.

Example 1: Replacing an Element

let arr = [10, 20, 30, 40, 50];
let newArr = arr.with(1, 15);
console.log(newArr); 
// Output: [ 10, 15, 30, 40, 50 ]

Example 2: Using Negative Indices

let arr = [10, 20, 30, 40, 50];
let newArr = arr.with(-1, 99);
console.log(newArr); 
// Output: [ 10, 20, 30, 40, 99 ]

Example 3: Modifying Nested Arrays

let arr = [[1, 2], [3, 4], [5, 6]];

let newArr = arr.with(1, [7, 8]);
console.log(newArr); 
// Output: [[1, 2], [7, 8], [5, 6]]

Supported Browsers

BrowserSupport
Chrome110+
Firefox109+
Safari16.4+
Edge110+
Opera96+
Internet ExplorerNot Supported

JavaScript, Web Technologies Tags:JavaScript-Array, JavaScript-Array-Method, JavaScript-Method

Post navigation

Previous Post: JavaScript Array values() Method
Next Post: JavaScript Array filter() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme