FOLASAYO SAMUEL OLAYEMI
SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

What is a pure function in JavaScript?

FOLASAYO SAMUEL OLAYEMI's photo
FOLASAYO SAMUEL OLAYEMI
·Jun 28, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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 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.

Code Sample Of a Pure Function:

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

Code Sample Of an Impure Function:

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)

Note:

  • 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.

Thanks for reading...

Happy Coding!

 
Share this