InterviewHubPRO
Section Overview
Q20

Question 20 of 521

Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)

4%
JavaScript Internals (521 Qs)•Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)

What are the benefits of pure functions

Some of the major benefits of pure functions are listed below,

  • Easier testing: Since output depends only on input, pure functions are simple to test.
  • Predictability: No hidden side effects make behavior easier to reason about.
  • Immutability: Pure functions align with ES6 best practices, such as preferring const over let, supporting safer and more maintainable code.
  • No side effects: Reduces bugs related to shared state or mutation.

Practical Code Example

javascript
// 1. Referential Transparency & Predictability
const add = (a, b) => a + b; // Always returns same output for same inputs

// 2. Easy Memoization / Caching
const memoize = (fn) => {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (!cache.has(key)) cache.set(key, fn(...args));
    return cache.get(key);
  };
};

const memoizedAdd = memoize(add);
console.log(memoizedAdd(5, 10)); // Computed: 15
console.log(memoizedAdd(5, 10)); // Served from cache: 15