JavaScript Methods – Why Are sort() and reverse() In-Place?

algorithmsimmutabilityjavascriptsorting

Which are the technical reasons/considerations for the sort() and reverse() JavaScript array methods to be in-place operations instead of returning a new array without modifying the original one, like the filter() or map() methods do?

I want to understand the technical reasons that drove such decision, why those methods do not follow immutability, and why was decided to modify the array in-place instead of returning a new array without modifying the original one… was it for performance reasons? technical constrains? which were the technical drivers of that decision?

Best Answer

Arrays were originally implemented as hash tables. Keys (buckets) were converted to strings and hashed. v8 still implements it as a hash table, but also supports a fixed array (ref).

The language specification (with updates) defines it as in-place, but I couldn't find a relevant design document regarding that decision.

My guess would be that the cost of duplicating the internal structure was relatively expensive at the time. It still can be depending on its size.

However, here's the official answer:

It was based on Java’s static method and also on Perl, both were in-place.