Xotic750
Xotic750

Reputation: 23482

Object/Array methods: Modify original or create new? Guidelines

With javascript we have methods like filter and map which do not modify the original array, but create a new array based on the supplied function.

We also have methods like sort which modify the original array.

The above are examples that are part of ECMA standards.

I also see tailored functions in libraries or GISTs, that do not conform to any standards or best practices.

Things like shuffle, often using algorithms like Fisher–Yates, which 90% of the time modify the original array but occasionally create a new array.

Methods like compress which remove holes in arrays, again often modifying the original array, but on occasion creating a new array.

So while investigating unique or removeDuplicates, I came across 3 possibilities.

function unique(array) {
    create newArray;
    push unique values into newArray;
    return newArray;
}

The above creates a new array of unique values, leaving the original array intact.

function unique(array) {
    remove duplicates from original array;
    return array;
}

The above modifies the original array as well as returning the reference to the original.

function unique(array) {
    create removedArray;
    remove duplicates from original array and push the removed elements into removedArray;
    return removedArray,
}

The above is similar to the previous except that it records the removed elements and returns them to me, kind of like splice.

This all got me to wondering if there are any standards or best practices when it comes to creating methods that work on Object or Array?

I haven't found any, do they exist?

If not, then I know this question can lead to opinion based answers, but it seems a sensible question to ask?

Upvotes: 2

Views: 1827

Answers (1)

Etheryte
Etheryte

Reputation: 25319

The ECMAScript Language Specification 5.1 (2011) doesn't outline why some methods modify the original object and why some others do not.

It only outlines, as an example, for Array.prototype.map (15.4.4.19) that

map does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.

without specifying a reason as to why this is the case.

However, for methods which do modify the original object, no special notice seems to be made outside the general description of the method. An example from the definition of Array.prototype.sort (15.4.4.11):

The elements of this array are sorted. [Rest of the definition follows.]

So to summarize:
In the cases where the original object is not modified, an explicit note is made about it, while in the cases where the original object is modified no special notice is added. Therefore it seems there is an implied standard that such methods modify the original object, however there is no explicit agreement or specification for it.

Upvotes: 1

Related Questions