Functional programming (FP) is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state or mutable data. Core principles include pure functions (same input always yields same output, no side effects), immutability, first-class and higher-order functions, and function composition. FP promotes code that is predictable, testable, and parallelisable, and is embodied in languages such as Haskell, Erlang, Clojure, and adopted extensively in Scala, F#, and modern JavaScript/Python.
| Aspect | Functional | Imperative | Example |
|---|---|---|---|
| State | Immutable | Mutable | val vs var |
| Control flow | Recursion, map/filter | Loops (for, while) | map() vs for loop |
| Side effects | Avoided / isolated | Common | IO monads vs direct I/O |
| Functions | First-class, higher-order | May be second-class | Passing functions as args |
| Debugging | Easier (pure functions) | Harder (shared state) | Unit testing pure fns |
| Performance | Can be lower (GC) | Can be higher (in-place) | Haskell vs C |
Wikimedia Commons, CC BY-SA
A closure is a function that retains access to the variables of its enclosing lexical scope even after that scope has finished executing. This allows inner functions to "close over" free variables from outer functions, preserving state without using global variables. Closures are fundamental to functional programming, event handling, and creating data privacy in languages like JavaScript, Python, and Go.
A lambda function is an anonymous, inline function expression defined without a formal name, typically used for short, single-use operations. Derived from lambda calculus (λ-calculus), lambda functions can be passed as arguments, returned from other functions, and stored in variables, making them essential to functional programming paradigms. They are supported in Python (lambda keyword), Java (->), JavaScript (=>), Haskell, and most modern languages.
The paradigm is rooted in Alonzo Church's lambda calculus (1930s). "Functional programming" as a term was popularised by John Backus in his 1977 Turing Award lecture "Can Programming Be Liberated from the von Neumann Style?", advocating FP over imperative style.