JavaScript Interview Question #177
What is a pure function?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
A pure function produces the same output for the same inputs and does not create observable side effects outside the function. It does not depend on hidden mutable state such as a changing global variable.
Detailed Explanation
A pure function produces the same output for the same inputs and does not create observable side effects outside the function. It does not depend on hidden mutable state such as a changing global variable.
Pure functions are easier to test, reason about, cache, and reuse. Real applications also require side effects such as network requests and DOM updates, so a useful design is to keep core calculations pure and isolate side effects at clear boundaries.
Code Example
function calculateTotal(price, quantity) {
return price * quantity;
}
console.log(calculateTotal(50, 3)); // 150
// No global state is read or changed.