JavaScript · Functional Programming · Fresh / Intern · Concept
What are pure functions and immutability, and why do they matter in JavaScript apps?
Short Interview Answer
Pure functions always return the same output for the same inputs without side effects; immutability avoids in-place mutation so data flow stays predictable.
Detailed Explanation
A pure function does not read/write external mutable state, perform I/O, or mutate its arguments. Immutability means updating data by creating new objects/arrays (or using structural sharing libraries) instead of changing existing ones. Benefits: easier testing, safer concurrency mentally, reliable memoization, and predictable UI rendering (e.g. React change detection). JS does not enforce purity — discipline and linting help. Prefer spreading/slicing carefully for shallow copies and know their limits with nested data.
Example
// impure
let total = 0;
function add(n) { total += n; return total; }
// pure
function addPure(total, n) {
return total + n;
}Interview Tip
Give a impure-vs-pure pair — quick and concrete.
Common Mistake
Calling a function pure if it only mutates a local object that was passed in from outside.