Skip to content
  • IIFE, Recursion & Pure Functions · JavaScript

IIFE, Recursion & Pure Functions

LearnViaNotes @learnvianotes· 2 min read

Three function ideas that show up constantly: run-once scopes, functions that call themselves, and functions with no side effects.

IIFE — Immediately Invoked Function Expression

JavaScript
const config = (() => {
  const env = "production";            // not visible outside
  return { env, debug: env !== "production" };
})();
console.log(config);

(function named() {
  console.log("runs immediately");
})();
Output
{ env: 'production', debug: false }
runs immediately

Recursion

JavaScript
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
const flatten = (arr) =>
  arr.reduce((acc, x) => (Array.isArray(x) ? acc.concat(flatten(x)) : acc.concat(x)), []);
function fib(n, memo = {}) {
  if (n <= 1) return n;
  return (memo[n] ??= fib(n - 1, memo) + fib(n - 2, memo));
}
console.log(factorial(5), flatten([1, [2, [3, [4]]]]), fib(50));
Output
120 [ 1, 2, 3, 4 ] 12586269025

Pure functions and side effects

JavaScript
const addItemImpure = (cart, item) => { cart.push(item); return cart; };
const addItemPure = (cart, item) => [...cart, item];

const cart = ["apple"];
const next = addItemPure(cart, "pear");
console.log(cart, next);
addItemImpure(cart, "plum");
console.log(cart);
Output
[ 'apple' ] [ 'apple', 'pear' ]
[ 'apple', 'plum' ]

What is a pure function and why does it matter?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report