A pure function always returns the same output for the same inputs, and has no side effects. Immutability means you do not change existing data. You make a new copy with the change instead.
A side effect is anything a function does besides returning a value. A pure function does none of these:
- change its arguments or outside variables
- do I/O, like network or file access
- read the current time or random numbers
- touch the DOM
For example, const add = (a, b) => a + b is pure. A function that pushes to a global array is not.
Pure functions are easy to test, understand, reuse and cache (memoize). They are also safe to run in parallel.
Immutability examples:
[...items, newItem]instead ofitems.push(newItem){ ...user, name }instead ofuser.name = name
It prevents bugs from shared references. It also makes change detection cheap: you just compare references. React, Redux and memoized selectors depend on this.
Real programs still need side effects. The goal is to keep them at the edges of the program, separate from the pure logic.
- A pure function gives the same output for the same input and has no side effects.
- Pure functions are easy to test, cache and understand.
- Immutability means creating new values instead of changing existing ones.
- Immutability enables change detection by comparing references, as React and Redux do.
- Keep side effects at the edges of the program.