Introduction to Functional Programming
🎯 Introduction
This article introduces the core ideas of functional programming and how they help you write well-structured, maintainable code. You will learn what it means for functions to be first-class values, how to write pure functions and avoid side effects, how higher-order functions process data, and how composition and currying improve reuse and readability.
🌀 What Is Functional Programming?
Functional programming is a programming paradigm centered on functions. It emphasizes describing program logic through functions rather than changing state and data. Think of a program as a composition of functions, each taking inputs and returning outputs instead of modifying external variables.
Why use functional programming?
Beginners often write imperative code with many variables and state changes that are hard to track. Functional programming can make code clearer and state more predictable, reduce bugs, and improve testing and reuse.
🔍 Functions as First-Class Values
In JavaScript, functions are first-class values, meaning:
- Functions can be stored in variables.
- Functions can be passed as arguments to other functions.
- Functions can be returned from other functions.
For example:
function greet(name) {
return 'Hello ' + name;
}
function sayHello(f) {
return f('Ming');
}
var message = sayHello(greet);
console.log(message); // Hello Ming
Passing greet to sayHello demonstrates that functions can be used as values.
💡 What Is a Pure Function?
A pure function:
- Always returns the same output for the same inputs.
- Has no side effects: it does not modify external variables, make network requests, or manipulate the DOM.
For example, this function is pure:
function add(a, b) {
return a + b;
}
Given 1 and 2, it always returns 3 without affecting anything outside the function.
The following function is not pure because it modifies an external variable:
var count = 0;
function increase() {
count = count + 1;
return count;
}
⚠️ What Are Side Effects, and Why Avoid Them?
A side effect is an observable change beyond returning a result, such as modifying global variables, mutating arguments, manipulating the DOM, or making network requests.
What problems can side effects cause?
- Behavior is harder to predict and debug because results depend on external state.
- Unit testing becomes more difficult.
- Code is harder to reuse.
Functional programming therefore encourages independent, pure functions and minimizes side effects where possible.
🎯 Higher-Order Functions
A higher-order function meets at least one of these conditions:
- It accepts one or more functions as arguments.
- It returns a function.
This makes functions highly flexible.
Examples:
JavaScript's built-in map, filter, and reduce are higher-order functions.
Suppose you want to double every number in an array:
var numbers = [1, 2, 3, 4];
var doubled = numbers.map(function (item) {
return item * 2;
});
console.log(doubled); // [2, 4, 6, 8]
Here, map accepts a function as its argument.
Now consider a function that returns another function:
function makeAdder(x) {
return function (y) {
return x + y;
};
}
var add5 = makeAdder(5);
console.log(add5(3)); // 8
makeAdder is a higher-order function that returns a new function with a customized addition operation.
🔗 Simple Function Composition
Function composition connects functions so that one function's output becomes the next function's input. We will use simple nested calls here, rather than a pipe utility.
Suppose we have two functions:
function double(n) {
return n * 2;
}
function square(n) {
return n * n;
}
To square a number and then double the result, write:
var result = double(square(3));
console.log(result); // 18
Execution proceeds from the inside out: square(3) returns 9, then double(9) returns 18.
Composition makes the structure and logic clear, with each function doing one thing.
🌀 What Is Currying?
Currying transforms a function that takes multiple arguments into a sequence of functions that each take one argument. This lets you partially apply arguments to create specialized functions.
For example:
function add(x) {
return function (y) {
return x + y;
};
}
var add10 = add(10);
console.log(add10(5)); // 15
Here, add accepts x and returns a new function that accepts y, then returns their sum.
Currying lets you create specialized functions. For example, add10 always adds 10 to its argument.
❓ Knowledge Check
Q1: What is a pure function? Give an example.
A pure function always returns the same output for the same inputs and has no side effects. For example: function add(a, b) { return a + b; }.
Q2: Why avoid side effects? Side effects make program state harder to manage and debug, and make code harder to reuse and test.
Q3: What is a higher-order function?
It accepts a function as an argument or returns a function. Examples include map and filter.
Q4: What is currying useful for? Currying makes it easy to create specialized functions, improving reuse and flexibility.
🧪 Exercises
Exercise 1: Write a pure function named multiply that accepts two numbers and returns their product.
function multiply(a, b) {
// Write your code here
}
Exercise 2: Write a higher-order function named repeat that accepts a function and a repetition count. Return a new function that calls the supplied function that many times.
function repeat(fn, times) {
// Write your code here
}
🎉 You now understand first-class functions, pure functions, higher-order functions, composition, and currying! Apply these ideas to make your code cleaner, more efficient, and easier to maintain.
