0

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

1

1 Answer 1

3

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:

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

3 Comments

For the record Array.from({length: x}, () => y) is the pure alternative to new Array(x).fill(y)
Yeah but we can also recognise that in the expression new Array(x).fill(y) the array created with new Array(x) is a throw away value, created on the fly for the purpose of filling it with new values. So in my mind it is pure in a way; it does mutate but in a controlled way and has no observable side effects. It's good to know about the alternative though.
Depends on how exactly it is used. .fill itself is impure but the construct new Array(x).fill(y) can be considered pure. Yet, it's context dependant, as arr = new Array(x); /* ... */ arr.fill(y) has a potential of other stuff happening in between. When we talk about purity, it's usually of a function, not a specific lines of code or combinations of those. So, if you had a function like makeArray = (x, y) => new Array(x).fill(y) that function is pure itself, as there is no observable side effect.

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.