0

When using the built-in methods available for arrays in Javascript, some methods will act directly on the calling array. For example, myArray.sort(), will sort myArray in ascending order, alphabetically or numerically.

myArray.sort();
// sort() acts directly on myArray, changing it in its place thereafter
// ... also myArray.reverse() amongst others.

While other methods such as slice(), require there be something, either a variable or other output for it to return its value to...

var need_a_new_array = myArray.slice(10, 21);
// a new placeholder is needed for the results of slice... if not using 
// the results immediately (i.e. passing to another function or 
// outputting the results)

I was wondering what is the proper terminology for these methods and their differences. I am using arrays as an example here, but I'm sure that the same probably holds true for objects in general. I appreciate any help. Thank you.

1

2 Answers 2

2

The correct terms are mutator and accessor.

A mutator method mutates (changes) the object it is called on, while an accessor accesses (and returns) the value of the object it is called on.

You can see examples of the two types by looking at the method listing for Array.prototype. Note that they are divided into categories, two of which are Mutator methods ("These methods modify the array") and Accessor methods ("These methods do not modify the array and return some representation of the array.")

Mutators can not be called on immutable objects.

See also this related question on the software engineering SE: What is the term used to describe a function/method that modifies the object it's called on?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Herohtar! Straight from MDN. Can't argue with that I guess.
0

The terms you're looking for are 'immutable' and 'mutable' . Array.prototype.sort is a mutable method in that it 'mutates' (changes) the original array, where as Array.prototype.slice is immutable as it creates a new array with the result and leaves the original array intact.

3 Comments

whoa thanks for such as super-fast and concise answer!
This isn't correct. "mutable" and "immutable" are terms referring to objects -- things that can be changed vs can't be.
Almost. The correct term is mutating vs non-mutating

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.