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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay