DEV Community

Discussion on: In-Place Algorithms; what are they, and why use them?

Collapse
 
mxldevs profile image
MxL Devs • Edited

Some languages like ruby come with "in-place" variations of a method. Arrays for example have tons of common stuff sort, reverse, etc. I could say array.sort which returns a new array, or I could just array.sort! which simply modifies it in-place. Initially I never understood the difference, but then it made more sense after reading about it.

Wonder if Javascript has something similar.

Collapse
 
hminaya profile image
Hector Minaya

Not everything is as it seems, in Ruby you can add elements dynamically to an array, which in reality just creates a new Array (based on the new size) and may keep the old one around until the garbage collector disposes of it.

Even JS has the ability to add/remove elements from an Array, because it's actually not an Array. It's a dictionary with an integer key and an object as it's value.

Collapse
 
seanwelshbrown profile image
Sean Welsh Brown

This is a really interesting point! It makes sense for higher level languages like Ruby that focus on "developer friendliness" to have options like that built in rather than coding them in yourself, and it's interesting to dig a bit deeper into the concept and see why having the option is important in the first place.

Thanks for the comment!

Collapse
 
varsity6177 profile image
Fredo

In JavaScript, array.sort() and array.reversed() are in-place. The out-of-place variants would be, respectively, toSorted() and toReversed().

Source: MDN