Javascript

JavaScript — Array with() method

Well, forget about the old and ugly way to update the value of some array. Description The with() method changes the value of a...

Written by Luci · 34 sec read >

Well, forget about the old and ugly way to update the value of some array.

const people = ["Kristiyan","Emiliyan", "Sally"];

people[2] = "Simon";
Result: ["Kristiyan", "Emiliyan", "Simon"];

Description

The with() method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations.

The with() method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with undefined in the new array.

The with() method is generic. It only expects this value to have a length property and integer-keyed properties.

Example

const people = ["Kristiyan","Emiliyan", "Sally"];

people.with(2, "Simon");
Result: ["Kristiyan", "Emiliyan", "Simon"];
Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile