Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
52 lines (39 sloc) 1.38 KB
author date layout slug title thumbnail template categories tags
Hoang Trinh
2020-03-18 09:01:00 +0000
post
what-is-pure-function
What is a pure function?
../thumbnails/question.png
post
Interview Questions
Javascript
interview-questions
javascript

What is a pure function?

Answer

A pure function is a function that satisfies these two conditions:

  • Given the same input, the function returns the same output.
  • The function doesn't cause side effects outside of the function's scope (i.e. mutate data outside the function or data supplied to the function).

Pure functions can mutate local data within the function as long as it satisfies the two conditions above.

Pure

const a = (x, y) => x + y
const b = (arr, value) => arr.concat(value)
const c = arr => [...arr].sort((a, b) => a - b)

Impure

const a = (x, y) => x + y + Math.random()
const b = (arr, value) => (arr.push(value), arr)
const c = arr => arr.sort((a, b) => a - b)

Good to hear

  • Pure functions are easier to reason about due to their reliability.
  • All functions should be pure unless explicitly causing a side effect (i.e. setInnerHTML).
  • If a function does not return a value, it is an indication that it is causing side effects.

Additional links

You can’t perform that action at this time.