DEV Community

Cover image for JavaScript - Array with() method
Kristiyan Velkov
Kristiyan Velkov

Posted on • Edited on

8 2 2 3 2

JavaScript - Array with() method

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

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

Browser's compatibility

Image description


Image description

linkedin


Image description

If you like my work and want to support me to work hard, please donate via:

Revolut website payment or use the QR code above.

Thanks a bunch for supporting me! It means a LOT 😍

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (4)

Collapse
 
eboye profile image
eboye

No Firefox, no ♥️

Collapse
 
kristiyanvelkov profile image
Kristiyan Velkov

yeah, so sad!

Collapse
 
jjaijg profile image
Jai Ganesh J

What is the browser compatibility for this method?

Collapse
 
kristiyanvelkov profile image
Kristiyan Velkov

Very good question. Thank you!
I will update the article with this information.

Best regards,
Kristiyan

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay