Arrays are fundamental building blocks in programming.We are familiar with accessing any element and changing its value with tradition method i.e using index and square bracket notation
while that is a common way, JavaScript offers new & alternative method i.e array.with(). This method is used to replace the value of an element at a specific index in an array with a new value, while returning a new array with the updated elements. The method takes two arguments: the index of the element to be replaced, and the new value to be assigned to that index
arr.with(index,value)
Advantages of this method over bracket notation is, by giving negative index, it is possible to traverse in reverse order of array eliminating the need for calculations like array.length - number
If there are empty slots in original array , then this method replaces it with undefined and return a new array
const arr = [1, 2, , 4,];
console.log(arr.with(1, 8)); // [1, 8, undefined ,4]
Top comments (0)