Functions in Node.js
Functions are everywhere in Node.js. They are the building blocks of everything — from simple scripts to complex APIs.
Try it Yourself →Function Declarations
// Function declaration
function add(a, b) {
return a + b;
}
// Function expression
const multiply = function(a, b) {
return a * b;
};
// Arrow function (ES6)
const divide = (a, b) => a / b;
// Arrow function with body
const greet = (name) => {
const message = `Hello, ${name}!`;
return message;
};
Default Parameters
function createUser(name, role = "user", active = true) {
return { name, role, active };
}
createUser("Alice"); // { name: "Alice", role: "user", active: true }
createUser("Bob", "admin"); // { name: "Bob", role: "admin", active: true }
Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15
Closures
Functions remember the variables from where they were created:
function createCounter() {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.getCount(); // 2
This pattern is incredibly common in Node.js. Closures let you create private state without classes.
Higher-Order Functions
Functions that take other functions as arguments:
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
repeat(3, (i) => console.log(`Iteration ${i}`));
// Array methods use higher-order functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const total = numbers.reduce((sum, n) => sum + n, 0);