JavaScript treats functions as first-class citizens, meaning they behave like normal values:
- Stored in variables
- Passed into other functions as arguments
- Returned from functions
- Assigned as object properties
This capability enables three foundational pillars of modern JavaScript:
- First-Class Functions
- Callbacks
- Closures
Together, these form the backbone of asynchronous programming, event handling, functional programming, React hooks, and Node.js architecture.
1. First-Class Functions
A language has first-class functions when functions behave like normal values (numbers, strings, objects).
Functions Stored in Variables
You can store a function in a variable just like any standard value:
const greet = function () {
console.log("Hello!");
};
greet(); // Output: Hello!Functions Passed as Arguments
You can send a function as a parameter into another function, and that receiving function can execute it.
🧠 Think of it like giving a tool to a machine:
- You provide
run()with a tool (a function). - Inside
run(), it uses that tool:tool(). - In memory, the parameter
fnpoints directly to the function you passed in.
function run(fn) {
fn(); // <-- Executes the function received
}
run(() => console.log("Running..."));
// Output: Running...Functions Returned from Other Functions
Functions can generate and return new functions, enabling factory functions and function generators:
function makeMultiplier(x) {
return function (y) {
return x * y;
};
}
const double = makeMultiplier(2);
console.log(double(5)); // Output: 102. Callbacks
A callback is a function passed into another function to run later.
Callbacks appear everywhere in JavaScript:
- Timers (
setTimeout,setInterval) - Event listeners (
element.addEventListener) - Array methods (
map,filter,reduce)
Callbacks allow asynchronous, non-blocking execution—JavaScript continues running other code while waiting for events or timers.
// 1. Simple Custom Callback
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
greet("Mohammed", () => console.log("Welcome!"));
// Output:
// Hello Mohammed
// Welcome!
// 2. Array Callback Example
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled); // Output: [2, 4, 6]
// 3. Asynchronous Callback Example
setTimeout(() => {
console.log("This runs later");
}, 2000);
// Output after 2 seconds: This runs later3. Closures (The Heart of JavaScript)
A closure happens when an inner function "remembers" and retains access to variables from its outer lexical scope—even after the outer function has finished executing.
Closures allow:
- Private variables (Encapsulation)
- Factory functions
- Function generators
- Event handler logic & stateful callbacks
- Module patterns
// 1. Basic Closure
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3
// 2. Encapsulation & Private Data
function createUser(name) {
let score = 0;
return {
getName: () => name,
addPoint: () => score++,
getScore: () => score
};
}
const user = createUser("Sara");
user.addPoint();
user.addPoint();
console.log(user.getName()); // Output: Sara
console.log(user.getScore()); // Output: 2
console.log(user.score); // Output: undefined (score is truly private!)Closures + Callbacks Working Together
When you pass a callback or create an event listener, closures allow that callback to carry its surrounding state with it:
function setupButton(text) {
return function handleClick() {
console.log("Clicked: " + text);
};
}
const clickFn = setupButton("Save");
clickFn(); // Output: Clicked: SavePillar | Definition | Key Powers | Common Use Cases |
|---|---|---|---|
First-Class Functions | Functions behave like standard values | Can be stored in variables, passed as args, and returned | Higher-order functions, functional programming, React components |
Callbacks | A function passed to another function to run later | Enables non-blocking asynchronous & event-driven execution | setTimeout, DOM events, array methods (map, filter, reduce) |
Closures | Inner function captures outer lexical scope variables | Encapsulates private data and preserves state across function calls | Factory functions, private state, React useState, memoization |
Think it throughQuick Interview Check: How do First-Class Functions, Callbacks, and Closures work together in array methods?
Consider nums.map(n => n * multiplier):
- First-class functions allow passing
n => n * multiplieras an argument. - That passed function is a callback that
.map()invokes on each array element. - It forms a closure over
multiplierfrom the surrounding scope, reading its value on every iteration.