Overview & Purpose
A function is a reusable block of code that performs a specific task. You define it once and can execute (call) it as many times as needed, with different inputs each time.
Why functions exist:
Without functions, you'd repeat the same code everywhere:
// ❌ WITHOUT functions — repetitive
console.log("₹" + (1000 + 1000 * 0.18).toFixed(2));
console.log("₹" + (2500 + 2500 * 0.18).toFixed(2));
console.log("₹" + (750 + 750 * 0.18).toFixed(2));
// ✅ WITH a function — write once, use many times
function addGST(price) {
return "₹" + (price + price * 0.18).toFixed(2);
}
console.log(addGST(1000));
console.log(addGST(2500));
console.log(addGST(750));Functions are the building blocks of JavaScript programs. Every button click handler, API call, form validator, and data transformer is a function.
Topic Definition
A JavaScript function is a named, callable block of code. It:
Takes inputs (called parameters/arguments)
Performs operations using those inputs
Returns an output (optional — default return value is undefined)
JavaScript has several ways to define functions:
| Type | Syntax | Key Feature |
|------|--------|-------------|
| **Declaration** | `function name() {}` | Hoisted — can be called before it's defined |
| **Expression** | `const fn = function() {}` | Not hoisted — assigned to a variable |
| **Arrow** | `const fn = () => {}` | No own `this` — concise syntax |
| **Method** | `{ fn: function() {} }` | Defined inside an object |
| **Immediately Invoked (IIFE)** | `(function() {})() ` | Runs once immediately |
Why It Matters
Functions solve the DRY principle (Don't Repeat Yourself). Every time you find yourself copy-pasting the same logic, that logic should be a function.
Key benefits:
1. Reusability — write once, call many times
2. Abstraction — hide complex logic behind a simple name
3. Testability — test each function in isolation
4. Readability — calculateGST(price) is clearer than the formula written inline
5. Maintainability — fix a bug in one place, fixed everywhere
Real-world functions you write constantly:
validateEmail(email) — check format
formatCurrency(amount) — display as ₹1,299
fetchUserData(userId) — API call
updateCartTotal(cart) — recalculate total
renderProductCard(product) — create HTML
Syntax Guide
// ═══════════════════════════════════════════════
// 1. FUNCTION DECLARATION (traditional)
// ═══════════════════════════════════════════════
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Asha")); // Hello, Asha!
// ═══════════════════════════════════════════════
// 2. FUNCTION EXPRESSION
// ═══════════════════════════════════════════════
const addNumbers = function(a, b) {
return a + b;
};
console.log(addNumbers(5, 3)); // 8
// ═══════════════════════════════════════════════
// 3. ARROW FUNCTION (modern, concise)
// ═══════════════════════════════════════════════
const multiply = (a, b) => a * b;
console.log(multiply(4, 5)); // 20
// ═══════════════════════════════════════════════
// 4. DEFAULT PARAMETERS
// ═══════════════════════════════════════════════
function createUser(name, role = "viewer", active = true) {
return { name, role, active };
}
console.log(createUser("Ravi"));
console.log(createUser("Priya", "admin"));
// ═══════════════════════════════════════════════
// 5. REST PARAMETERS (variable number of args)
// ═══════════════════════════════════════════════
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15- Parameters — named variables in the function definition: function fn(param1, param2) {}
- Arguments — actual values passed when calling: fn(value1, value2)
- Default parameters — fallback values when argument is undefined: function fn(x = 10) {}
- Rest parameters — collects remaining args into array: function fn(...args) {}
- return — sends a value back to the caller. Without return, the function returns undefined
Functions return undefined by default. Use the return keyword to send back any value — number, string, object, array, boolean, or another function.
How function calls work (call stack):
1. call greet("Asha")
2. Create new execution context
3. name = "Asha"
4. Execute: return "Hello, " + name + "!"
5. Return "Hello, Asha!" to caller
6. Remove function from call stackParameters vs Arguments:
Parameters are placeholders in the definition: function add(a, b) — a and b are parameters
Arguments are the real values you pass: add(5, 3) — 5 and 3 are arguments
Return value rules:
Functions without return → return undefined
return; with no value → returns undefined
return value; → returns that value and STOPS the function
After a return statement, no more code in the function runs
Runnable Code Examples
Example 1: Function Declaration vs Expression vs Arrow
All three ways to define the same function — with key differences.
// 1. Function Declaration — hoisted, callable before definition
function calculateGST(price) {
return price * 0.18;
}
// 2. Function Expression — not hoisted, assigned to variable
const calculateGST2 = function(price) {
return price * 0.18;
};
// 3. Arrow Function — concise, no own 'this'
const calculateGST3 = (price) => price * 0.18;
// All three do the same thing
console.log(calculateGST(1000)); // 180
console.log(calculateGST2(1000)); // 180
console.log(calculateGST3(1000)); // 180
// HOISTING demonstration
console.log(hoisted("World")); // Works! ✅
function hoisted(name) { return "Hello " + name; }
// console.log(notHoisted("World")); // ❌ TypeError — not hoisted
const notHoisted = (name) => "Hello " + name;Function declarations are hoisted — you can call them before the code that defines them. Function expressions and arrow functions are NOT hoisted. The practical choice: use function declarations for named utilities, arrow functions for callbacks.
Example 2: Parameters, Arguments, and Return Values
Complete guide to function inputs and outputs.
// Basic parameters and return
function getFullName(firstName, lastName) {
return firstName + " " + lastName;
}
// Default parameters — used when argument is missing/undefined
function createProfile(name, role = "user", verified = false) {
return {
name: name,
role: role,
verified: verified,
createdAt: new Date().toISOString().split("T")[0]
};
}
// Rest parameters — collect unlimited arguments
function calculateTotal(...prices) {
return prices.reduce((sum, price) => sum + price, 0);
}
// Destructuring parameters
function displayUser({ name, email, role = "guest" }) {
return name + " <" + email + "> [" + role + "]";
}
console.log(getFullName("Asha", "Sharma"));
console.log(createProfile("Ravi"));
console.log(createProfile("Priya", "admin", true));
console.log(calculateTotal(1299, 499, 2499, 149));
console.log(displayUser({ name: "Mira", email: "mira@example.com" }));Default parameters prevent undefined errors. Rest parameters (...) collect unlimited arguments into an array. Destructuring parameters directly unpack objects — common in React component props.
Example 3: Functions as First-Class Citizens
JavaScript functions can be passed as arguments, returned, and stored in variables.
// Functions stored in variables (function expressions)
const greet = (name) => "Hello, " + name;
// Functions passed as arguments (callbacks)
function applyOperation(numbers, operation) {
return numbers.map(operation);
}
const double = n => n * 2;
const square = n => n * n;
const addTax = n => +(n * 1.18).toFixed(2);
const prices = [100, 200, 300];
console.log("Doubled:", applyOperation(prices, double));
console.log("Squared:", applyOperation(prices, square));
console.log("With tax:", applyOperation(prices, addTax));
// Functions returned from functions (higher-order functions)
function createMultiplier(factor) {
return (number) => number * factor;
}
const triple = createMultiplier(3);
const tenX = createMultiplier(10);
console.log("Triple 5:", triple(5));
console.log("10x of 7:", tenX(7));Functions as first-class citizens means they can be stored, passed, and returned. This enables powerful patterns: callbacks (event handlers, array methods), higher-order functions (map, filter, reduce), and factory functions (createMultiplier).
Example 4: Real-World Utility Functions
The exact kind of functions you write in production JavaScript every day.
// ─── Form Validation ──────────────────────────────────────────────
function validateEmail(email) {
return email.includes("@") && email.includes(".") && email.length >= 5;
}
// ─── Currency Formatting ───────────────────────────────────────────
function formatINR(amount) {
return "₹" + amount.toLocaleString("en-IN", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
// ─── Text Processing ───────────────────────────────────────────────
function truncate(text, maxLen = 100) {
if (text.length <= maxLen) return text;
return text.slice(0, maxLen).trim() + "...";
}
// ─── Date Formatting ──────────────────────────────────────────────
function formatDate(dateStr) {
const d = new Date(dateStr);
return d.toLocaleDateString("en-IN", {
day: "2-digit",
month: "short",
year: "numeric"
});
}
// ─── Tests ────────────────────────────────────────────────────────
console.log(validateEmail("asha@example.com"));
console.log(validateEmail("invalid-email"));
console.log(formatINR(1234567.89));
console.log(truncate("This is a very long product description that exceeds the limit", 30));
console.log(formatDate("2026-06-01"));These utility functions are the backbone of real apps. Validate before submit, format before display, truncate for card layouts, format dates for readability. Each does ONE thing, which makes them reusable and testable.
Real-world Use Cases
- 1
Event handlers: Every
addEventListenercallback is a function —button.addEventListener('click', handleSubmit)wherehandleSubmitis defined elsewhere. - 2
API calls:
async function fetchProducts(category) { const res = await fetch(...); return res.json(); }— fetches and returns data. - 3
Form validation:
validateForm(formData)checks all fields and returns{ valid: true }or{ valid: false, errors: [...] }. - 4
Data transformation:
formatProductsForDisplay(apiResponse)converts raw API data to display-ready format with formatted prices, truncated descriptions. - 5
React components: Every React component is a function that takes props and returns JSX —
function ProductCard({ product }) { return <div>...</div>; } - 6
Utility libraries: Format, validate, parse — every utility function you write that gets reused across the app.
- 7
Factory functions:
createAuthHeader(token)generates the right header object for API requests, centralizing authentication logic.
Coding Exercises
Exercise Challenge
Write a function calculateOrderTotal(items) that takes an array of {price, qty} objects and returns the total with 18% GST.
Exercise Challenge
Write a createCounter(start, step) function that uses closure to track and increment a counter.
Practice Tasks Checklist
JavaScript Functions Quiz Challenges
Quiz Challenge
What does a function return if it has no return statement?
Quiz Challenge
What is the difference between a function declaration and a function expression regarding hoisting?
Quiz Challenge
What is the correct way to pass a function as an argument to setTimeout?
Quiz Challenge
What are rest parameters used for?
Technical Interview Q&As
1What is the difference between function declaration and function expression?
Model Answer:
Function declaration: `function name() {}` — hoisted completely, callable before its position in code. Function expression: `const fn = function() {}` or arrow `const fn = () => {}` — not hoisted, only accessible after the assignment line. Practical difference: use declarations for named utility functions, expressions/arrows for callbacks and inline logic.2What does it mean that functions are 'first-class citizens' in JavaScript?
Model Answer:
In JavaScript, functions are values just like numbers or strings. This means: they can be stored in variables (const fn = function(){}), passed as arguments to other functions (array.map(fn)), returned from functions (return function(){}), and stored in objects/arrays. This enables higher-order functions, callbacks, closures, and functional programming patterns.3What is the difference between parameters and arguments?
Model Answer:
Parameters are the named variables in the function definition: `function add(a, b)` — a and b are parameters. Arguments are the actual values passed when calling the function: `add(5, 10)` — 5 and 10 are arguments. JavaScript doesn't enforce the number of arguments — missing args are undefined, extra args are ignored (unless using rest parameters).4What is a pure function?
Model Answer:
A pure function always produces the same output for the same input (deterministic) and has no side effects (doesn't modify external state, make API calls, or update the DOM). Example: `const add = (a, b) => a + b` is pure. Pure functions are easier to test, debug, and reason about. Array methods like map, filter, reduce work best with pure callback functions.5What is a higher-order function?
Model Answer:
A higher-order function either takes a function as an argument or returns a function (or both). Examples of built-in HOFs: array.map(fn), array.filter(fn), array.reduce(fn, init), setTimeout(fn, delay). Examples you write: `function applyTwice(fn, x) { return fn(fn(x)); }`. They enable composition, abstraction, and functional patterns.6What is a closure?
Model Answer:
A closure is a function that remembers and can access variables from its outer scope even after the outer function has returned. Example: `function createCounter() { let count = 0; return () => ++count; }` — the inner arrow function closes over `count`. Each call to createCounter() creates a NEW, independent counter. Closures enable private state, factory functions, and memoization.