Function Basics
Functions are the fundamental building blocks of JavaScript.
They let you wrap reusable logic into a named block, accept
parameters as input, and
return a value as output.
Every great JavaScript program is built from well-designed functions —
mastering them unlocks everything from DOM manipulation to async programming.
return statement
What Is a Function?
A function is a reusable, named block of code that performs a specific task. Instead of writing the same logic multiple times, you define it once as a function and call it whenever you need it. Functions also make your code easier to read, test, and debug.
// function body — your logic goes here
const message = `Hello, ${name}! You are ${age} years old.`;
return message; // sends a value back to the caller
}
// ── Define a function ────────────────────────────────────────
function greet(name) {
return `Hello, ${name}!`;
}
// ── Call (invoke) the function ───────────────────────────────
const msg = greet("Alice"); // "Hello, Alice!"
console.log(msg);
// ── Call it again with different arguments ───────────────────
console.log(greet("Bob")); // "Hello, Bob!"
console.log(greet("Carol")); // "Hello, Carol!"
// ── Function with no parameters ──────────────────────────────
function sayHello() {
console.log("Hello, World!");
}
sayHello(); // Hello, World!
// ── Function with no return (returns undefined implicitly) ───
function logSum(a, b) {
console.log(a + b); // logs the result
// no return → returns undefined
}
const result = logSum(2, 3); // logs 5
console.log(result); // undefinedgreet("Alice"), name is
the parameter and "Alice" is the argument.
4 Ways to Define a Function
JavaScript gives you four syntax options for creating functions.
Each has different behaviour around hoisting, the this keyword,
and verbosity. Choosing the right one for the right job is a hallmark of clean JS code.
function keyword. Can
be called before it appears in the file thanks to hoisting.thisthis=>. Inherits
this from the surrounding scope. Perfect for callbacks.
thisnew Function(). Rarely used — avoid in production.
// ── 1. Function Declaration ───────────────────────────────────
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
// ── 2. Function Expression ───────────────────────────────────
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
// ── 3. Arrow Function (ES6) ───────────────────────────────────
const subtract = (a, b) => a - b; // one-liner implicit return
console.log(subtract(10, 4)); // 6
const divide = (a, b) => { // multi-line arrow with explicit return
if (b === 0) return null;
return a / b;
};
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // null
// ── 4. Function Constructor (avoid in production) ────────────
const square = new Function("x", "return x * x");
console.log(square(6)); // 36 (works, but slow & unsafe)
Parameters, Arguments & Return
Understanding how data flows into a function via
parameters and back out via return
is the core of writing useful functions. JavaScript is flexible — you can pass
more or fewer arguments than the function declares, use default values, and
collect any number of arguments with rest parameters.
| Concept | Syntax | Description |
|---|---|---|
| Regular param | function f(a, b) |
Named placeholder — receives the argument passed at that position |
| Default param | function f(a, b = 10) |
Used when no argument (or undefined) is passed for that position |
| Rest param | function f(a, ...rest) |
Collects all remaining arguments into an array — must be last |
| return | return value; |
Sends a value back to the caller and exits the function immediately |
| No return | (omit return) | Function implicitly returns undefined |
| Early return | if (x) return; |
Exit the function early — great for guard clauses |
// ── Regular parameters ───────────────────────────────────────
function sum(a, b) { return a + b; }
sum(3, 4); // 7
sum(3); // NaN (b is undefined → 3 + undefined = NaN)
// ── Default parameters (ES6) ─────────────────────────────────
function power(base, exponent = 2) {
return base ** exponent;
}
power(3); // 9 (exponent defaults to 2)
power(2, 10); // 1024
// ── Rest parameters ──────────────────────────────────────────
function total(label, ...numbers) {
const s = numbers.reduce((acc, n) => acc + n, 0);
return `${label}: ${s}`;
}
console.log(total("Score", 10, 20, 30)); // "Score: 60"
// ── return stops execution immediately ───────────────────────
function divide(a, b) {
if (b === 0) return "Cannot divide by zero"; // early return (guard)
return a / b;
}
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // "Cannot divide by zero"
// ── Returning multiple values via an object ───────────────────
function minMax(arr) {
return { min: Math.min(...arr), max: Math.max(...arr) };
}
const { min, max } = minMax([3, 1, 7, 2, 9]);
console.log(min, max); // 1 9const { min, max } = minMax(arr);
Hoisting
Hoisting is JavaScript's behaviour of moving
declarations to the top of their scope before code executes.
Function declarations are fully hoisted — you can call them
before they appear in your source code. Function expressions
and arrow functions are NOT hoisted because they are stored
in variables (const / let).
greet(); — works fine even though function greet()
is written later in the file.
const or let are in
the Temporal Dead Zone until their line is reached.
Calling them before definition throws a ReferenceError.
// ── ✅ Function declaration — hoisted ────────────────────────
console.log(add(2, 3)); // 5 — works! Called BEFORE definition
function add(a, b) { // defined AFTER the call above
return a + b;
}
// ── ❌ Function expression — NOT hoisted ─────────────────────
console.log(multiply(2, 3)); // ReferenceError: Cannot access before init
const multiply = function(a, b) { return a * b; };
// ── ❌ Arrow function — NOT hoisted ──────────────────────────
console.log(square(4)); // ReferenceError
const square = x => x * x;
// ── Why hoisting exists ───────────────────────────────────────
// JS engine does two passes:
// 1. PARSE phase → registers all function declarations
// 2. EXECUTE phase → runs the code top to bottom
// Function declarations are available in phase 1 → callable anywhere
// const/let variables are created in phase 2 → not accessible before their linePure Functions & Side Effects
A pure function always returns the same output for the same input and has no side effects — it doesn't modify variables outside its scope, make network calls, or write to the DOM. Pure functions are easier to test, debug, and reason about. Most well-designed programs aim to keep as much logic as possible in pure functions.
// ── ✅ Pure function — same input → same output, no mutations ─
function double(n) {
return n * 2; // depends only on n, changes nothing outside
}
double(5); // always 10
double(5); // always 10 — predictable!
// ── ❌ Impure — modifies external state (side effect) ────────
let total = 0;
function addToTotal(n) {
total += n; // mutates external variable — side effect!
}
addToTotal(5); // total is now 5
addToTotal(5); // total is now 10 — output depends on state
// ── ✅ Refactor: make it pure ─────────────────────────────────
function addValues(current, n) {
return current + n; // returns new value, doesn't mutate
}
const newTotal = addValues(total, 5); // 15
// ── Side effects that ARE acceptable ─────────────────────────
function saveUser(user) {
localStorage.setItem("user", JSON.stringify(user)); // I/O side effect
}
function renderTitle(text) {
document.title = text; // DOM side effect — intentional
}Real-World Function Patterns
These function patterns appear constantly in real JavaScript projects. Each demonstrates a clean, idiomatic way to write functions for common tasks.
true/false — clean and
reusable across the app.// ── Utility: celsius to fahrenheit ───────────────────────────
const toFahrenheit = c => (c * 9 / 5) + 32;
console.log(toFahrenheit(100)); // 212
// ── Validator: check email format ────────────────────────────
function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
isValidEmail("a@b.com"); // true
isValidEmail("not-an-email");// false
// ── Factory: create a user object ────────────────────────────
function createUser(name, role = "viewer") {
return { id: Date.now(), name, role, createdAt: new Date() };
}
const user = createUser("Alice", "admin");
// ── Transformer: format currency ─────────────────────────────
const formatCurrency = (amount, currency = "USD") =>
new Intl.NumberFormat("en-US", { style: "currency", currency }).format(amount);
console.log(formatCurrency(1234.56)); // "$1,234.56"
// ── Guard clause: validate input first ───────────────────────
function getDiscount(price, member) {
if (typeof price !== "number" || price <= 0) return 0;
if (!member) return price * 0.05; // 5% for non-members
return price * 0.15; // 15% for members
}
// ── Callback: event handler ───────────────────────────────────
const handleClick = (event) => {
console.log(`Clicked: ${event.target.id}`);
};
document.getElementById("myBtn")?.addEventListener("click", handleClick);
Try It — Live Editor
Experiment with JavaScript functions below. Modify parameters, change return values, and try all four definition styles — all without leaving this page.
Common Pitfalls & Best Practices
Avoid these common mistakes that trip up beginners and even experienced developers when working with functions.
// ── ❌ Pitfall 1: calling a function without () ───────────────
function greet() { return "Hello"; }
const a = greet; // ❌ assigns the FUNCTION itself, not its result
const b = greet(); // ✅ calls the function → "Hello"
// ── ❌ Pitfall 2: forgetting to return ───────────────────────
function square(n) {
n * n; // ❌ computes but never returns — result is lost
}
console.log(square(5)); // undefined
// ✅ Fix: add return
function squareFix(n) { return n * n; }
// ── ❌ Pitfall 3: too many parameters → hard to call ─────────
function createUser(name, age, role, email, active) { ... } // confusing!
// ✅ Fix: use a single options object
function createUser({ name, age, role = "viewer", email, active = true }) {
return { name, age, role, email, active };
}
createUser({ name: "Alice", age: 30, email: "a@b.com" }); // clean!
// ── ❌ Pitfall 4: arrow function returning an object literal ─
const getUser = name => { name }; // ❌ {} is treated as function body!
// ✅ Fix: wrap the object in parentheses
const getUserFix = name => ({ name }); // ✅ returns { name }
// ── ✅ Keep functions small and single-purpose ───────────────
// A function should do ONE thing and do it well.
// If your function is over 20 lines, consider splitting it.getUser(), calculateTax(), isValid(),
formatDate(). Avoid vague names like doStuff() or
process(). A well-named function is self-documenting.
return statement?const f = name => { name };
- A function is a reusable, named block of code. You define
it once with the
functionkeyword (or alternatives) and call it withfunctionName(). - JavaScript has four ways to define functions: declaration,
expression, arrow function (ES6), and the rarely-used
new Function()constructor. - Parameters are placeholders in the definition; arguments
are the values passed when calling. Functions can have default params
(
b = 10) and rest params (...rest). - The
returnstatement sends a value back to the caller and exits the function immediately. Without it, the function returnsundefined. - Function declarations are hoisted — they can be called before they appear in code. Function expressions and arrow functions are NOT hoisted.
- A pure function always returns the same result for the same input and has no side effects. Aim for pure functions wherever possible.
- In arrow functions, returning an object literal requires wrapping it in parentheses:
() => ({ key: value })— otherwise{}is treated as a function body. - Keep functions small, focused, and well-named. A function should do one thing. If it's over ~20 lines, consider splitting it.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.