Search code examples
javascriptfunctional-programming

Which functions in Array.prototype are pure function in Javascript


I know the the pure functions has some rules below.

  1. no side effect.
  2. always same input & same out when you call this function.

could someone help me list out the all pure functions in Javascript until ES2020?

I know slice is a pure function

Array.prototype.slice


Solution

  • Note: This list includes the first standard the method appears in. For clarity for older standards:

    • [ES1997] is ES1 - 1st edition of the ECMAScript standard
    • [ES1999] is ES3 - 3rd edition of the ECMAScript standard
    • [ES2009] is the 5.0 version of the ECMAScript standard, it has been revised in 2011 as 5.1, however no new relevant methods have been added in there

    Array static methods

    Array instance methods

    1 These accept a callback parameter. While the method will not itself alter any of the arguments, the callback might. So, technically it's possible to pass an impure callback which makes the whole operation impure.

    2 Returns an iterator. The operation is pure but using the iterator is not. For example, you might get different results if you get all the values of the iterator immediately or you get some, then the array is altered in-place, then you continue getting values from the iterator.

    3 Technically pure by its operation but the expectation is that the callback it accepts will have side effects. If the callback doesn't have side effects, it's likely not going to be a useful operation.

    4 This is a pure version of an existing method. Instead of mutating the current instance, it returns a new array with the operation applied to it.


    References: