Return Values & Pure Functions
Functions can return values using the return keyword. Pure functions always produce the same output for the same input and have no side effects — they are the foundation of reliable, testable code.
Return & Pure Functions
- return — Sends a value back to the caller AND exits the function immediately
- No return — Function returns undefined by default if no return statement
- Single responsibility — Each function should do ONE thing well
- Pure function — Same input always gives same output. No side effects (no modifying external variables)
- Impure function — Depends on external state, modifies external variables, or produces side effects (console.log, DOM updates, API calls)
- Why pure? — Predictable, testable, reusable. No hidden surprises
Return & Pure Functions Code
// Return value
function multiply(a, b) {
return a * b; // returns the result
console.log("Hi"); // ❌ Never runs! return exits function
}
const result = multiply(5, 3);
console.log(result); // 15
// No return = undefined
function sayHello(name) {
console.log("Hello, " + name);
// no return statement
}
const value = sayHello("Alice");
console.log(value); // undefined
// ✅ Pure function — same input = same output
function calculateTax(price, rate) {
return price * rate;
}
console.log(calculateTax(100, 0.18)); // Always 18
console.log(calculateTax(100, 0.18)); // Always 18
// ❌ Impure function — depends on external state
let taxRate = 0.18;
function calculateTaxImpure(price) {
return price * taxRate; // depends on external taxRate
}
// If taxRate changes, same input gives different output!
// ✅ Pure: Array operations
function doubleAll(numbers) {
return numbers.map(n => n * 2); // returns NEW array
}
const original = [1, 2, 3];
const doubled = doubleAll(original);
console.log(original); // [1, 2, 3] — unchanged!
console.log(doubled); // [2, 4, 6]Tip
Tip
Make functions pure whenever possible — same input always produces same output, no side effects. Pure functions are easier to test, debug, and reuse. Reserve impure functions for I/O operations (API calls, DOM updates, logging).
Function + environment.
Common Mistake
Warning
Forgetting to return a value from a function. If your function calculates something but doesn't use 'return', it returns undefined. Common bug: function add(a, b) { a + b; } — missing return! Should be: return a + b;
Practice Task
Note
Practice pure vs impure: (1) Write a pure function that calculates tax (price, rate) => price * rate. (2) Write a pure function that filters an array without modifying the original. (3) Identify why console.log inside a function makes it impure.
Quick Quiz
Key Takeaways
- Functions can return values using the return keyword.
- return — Sends a value back to the caller AND exits the function immediately
- No return — Function returns undefined by default if no return statement
- Single responsibility — Each function should do ONE thing well