DEV Community

Cover image for Lesser know JavaScript array methods part -1
ShreenidhiBatavi
ShreenidhiBatavi

Posted on

Lesser know JavaScript array methods part -1

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)
Enter fullscreen mode Exit fullscreen mode

array.with() method

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

array.with() method

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]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)