.with()
Armstrong20355 total contributions
Published Jul 30, 2023
Contribute to Docs
The .with()
method modifies the value of an element in an array. Since .with()
is a copying method, it creates a new array.
Syntax
arrayName.with(index, value);
.with()
takes the following parameters:
index
: The location of the array element to be altered.value
: The updated value for the array element.
Examples
Create and modify an array of colors.
let favoriteColors = ['blue', 'red', 'brown', 'grey'];// Updating red to purplefavoriteColors.with(1, 'purple');console.log(favoriteColors);
This results in the following output:
blue, red, brown, grey
Note:
.with()
was used to change'red'
to'purple'
in the example above. However,console.log(favoriteColors)
still printsred
. The reason is that.with()
does not modify an array, it returns a new array.
// Create an array of favorite colors.let favoriteColors = ['blue', 'red', 'brown', 'grey'];console.log(favoriteColors.with(1, 'purple'));
This results in the following output:
blue, purple, brown, grey
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.