Functional Programming: Functions, Recursion and Immutability with a Worked Trace

Trace one JavaScript cart pipeline to see how functions as values, recursive reduction and immutable updates work together without changing the input.

KnowledgeGate Team

Exam prep & CS education

Updated 22 Nov 20266 min read
Functional Programming: Functions, Recursion and Immutability with a Worked Trace

You may be able to recite that functional programming uses functions and avoids changing state, yet still struggle to predict a recursive result or explain why repeated calls should agree. One exact JavaScript cart pipeline connects the ideas. It starts with [250, 150, 75, 100], maps that cart to [200, 120, 60, 80], and recursively totals the new list to 460. Following those values will make functions, recursion and immutability concrete.

Functional programming expresses computation through values and functions

Functional programming builds results by evaluating and combining functions. It favours explicit inputs, returned outputs and immutable values. Real programs still read input, store data and produce output, so effects remain. Functional design keeps them at clear boundaries, making central transformations easier to reason about.

Three related ideas do different jobs. A function can be treated as a value and combined with other functions. Recursion defines a result through smaller instances plus a base case. Immutability means an existing value is not altered, so an update produces a new value. They reinforce one another, but are not synonyms. The Programming Languages Survey places this paradigm beside other language families. Functional and imperative features can coexist, so JavaScript is readable notation here, not a purely functional language.

Pure, first-class and higher-order functions have distinct roles

A pure function satisfies two conditions: the same explicit inputs give the same result, and evaluation causes no externally visible side effect. Consider const discount20 = price => price * 4 / 5;. It gives discount20(250) = 200 and discount20(150) = 120. Calling it again with 250 still returns 200, without changing a cart.

First-class functions are values that can be stored, passed or returned. A higher-order function takes or returns a function. In cart.map(discount20), discount20 is passed as a value, map is higher-order, and the result is a new array.

Composition joins these roles:

js
const totalAfterDiscount = prices => sum(prices.map(discount20));

Read it inside out. discount20 transforms each price, map collects the transformed values, and sum reduces the list to one number. Short arrow syntax alone proves nothing about purity. A short function that reads or changes hidden state can still be impure.

Worked example: map four prices, then sum recursively

The runnable cart example is:

js
const cart = Object.freeze([250, 150, 75, 100]);

const discount20 = price => price * 4 / 5;

function sum(xs) {
  if (xs.length === 0) return 0;
  const [head, ...tail] = xs;
  return head + sum(tail);
}

const totalAfterDiscount = prices =>
  sum(prices.map(discount20));

const total = totalAfterDiscount(cart);

Compute every mapped value before tracing the recursion:

  • 250 * 4 / 5 = 200

  • 150 * 4 / 5 = 120

  • 75 * 4 / 5 = 60

  • 100 * 4 / 5 = 80

Therefore, cart.map(discount20) produces [200, 120, 60, 80]. It does not rewrite cart in place. Adding the new values gives 200 + 120 + 60 + 80 = 460, so total = 460. A second call to totalAfterDiscount(cart) also returns 460, and cart remains [250, 150, 75, 100]. That stability comes from explicit inputs and pure helper functions, not memoisation or caching.

Pipeline diagram maps cart values 250, 150, 75, and 100 to 200, 120, 60, and 80, preserving the original and totaling 460.

Recursion needs a base case, progress and a complete trace

The base case is sum([]) = 0. The recursive step is sum([head, ...tail]) = head + sum(tail). Each call here shortens the list, with lengths 4 -> 3 -> 2 -> 1 -> 0, so the base case must be reached.

Expand the calculation without skipping a call:

Code
sum([200,120,60,80])
= 200 + sum([120,60,80])
= 200 + 120 + sum([60,80])
= 200 + 120 + 60 + sum([80])
= 200 + 120 + 60 + 80 + sum([])
= 460

The return values unwind as 0 -> 80 -> 140 -> 260 -> 460.

This semantic trace is separate from runtime implementation. Pending calls form before unwinding, so stack depth can matter for large inputs. Some implementations optimise particular recursive forms, but not every runtime removes every frame. When an assessment gives no optimisation guarantee, solve the value trace first and discuss space separately.

Two-sided recursion ladder for [200, 120, 60, 80] descends to base result 0 and ascends through returns ending at 460.

Immutability preserves old values while updates create new ones

const discounted = cart.map(discount20) binds a second array, [200, 120, 60, 80]; it does not replace elements inside cart. Rebinding and mutation are different. For a correction, const revisedCart = cart.map((p, i) => i === 2 ? 90 : p) produces [250, 150, 90, 100], while cart[2] remains 75.

A total calculation can trust that another helper did not silently change its input, earlier versions remain available, and independent functions are easier to test. Immutability does not eliminate every bug or make every operation free.

Two caveats matter. JavaScript const prevents variable rebinding but does not make an object deeply immutable, and Object.freeze is shallow. Persistent lists and trees can limit copying by sharing unchanged structure. In a singly linked [250,150,75,100], replacing 75 with 90 copies the changed path but can share the unchanged tail node 100.

How assessments test functional programming: traps, costs and paradigm choices

First, do not omit or mis-specify the base case. If this example used sum([]) = 1, every total would be one too high, producing 461. With no reachable base case, calls continue until the runtime fails. Write the empty-input result and prove that each call is smaller before tracing.

Second, familiar syntax does not guarantee purity:

js
let calls = 0;
const twice = x => { calls += 1; return 2 * x; };

The numeric return is predictable, but evaluating twice changes hidden state. Return the count as part of a new value, or keep the effect at an explicit boundary.

Third, do not assume every array method preserves its receiver. JavaScript map returns a new array, while methods such as sort can mutate the array they are called on. Check the operation's contract when the old order must remain observable.

Functional design also has costs. Allocation, retained versions and recursive stack depth can consume memory or time. Persistent structures, controlled effect boundaries and suitable iteration abstractions are practical responses. There is no forced choice between paradigms: Object Oriented Technology Explained shows the wider object model. Objects can contain pure functions and immutable values, while functional code can use modules and data abstractions.

Assessment questions typically ask you to predict a mapped array or recursive return, identify whether a function is pure or higher-order, distinguish rebinding from mutation, and compare stack or allocation costs. For a code trace, record the original input, every intermediate value and the base case. For a theory question, name the observable effect or mutation that makes a tempting statement false.

The short version: self-checks and next steps

Test your understanding against the same program:

  1. Derive the mapped list [200,120,60,80].

  2. Expand the recursive sum to 460.

  3. Name 0 as both the additive identity and the base result.

  4. State that cart[2] remains 75 after revisedCart is created.

  5. Identify map as higher-order because it receives discount20.

Then transfer the method. For input [50, 25], mapping gives [40, 20], and the recursive total is 60.

The decision rules are compact: track values instead of vague labels, ask whether output depends only on explicit inputs, find the base case and shrinking argument, distinguish a new value from an in-place change, and never assume stack optimisation that the question does not state.

For a structured preparation route, use GATE Guidance to sequence programming-language study, compare the wider Computer Science syllabus in the NTA-UGC-NET Paper 2 course, or review subject options in the GATE CS category.