Tutorials JavaScript Function Basics
Ch 23 / 78
Chapter 23 Beginner 9 min read JavaScript

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.

What you'll learn
How to declare and call a function
Parameters, arguments, and the return statement
Default parameters and rest parameters
4 ways to define a function in JavaScript
Hoisting — why function declarations can be called before they appear
Pure functions, side effects, and real-world patterns

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  greet(name, age)  {
    // function body — your logic goes here
    const  message = `Hello, ${name}! You are ${age} years old.`;
    return  message;  // sends a value back to the caller
}
keyword function name parameters return value
JavaScript — Defining & Calling a Function
// ── 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); // undefined
Parameters vs Arguments
Parameters are the variable names listed in the function definition — they are placeholders. Arguments are the actual values you pass when calling the function. In greet("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 declaration
Function Declaration
The classic syntax using the function keyword. Can be called before it appears in the file thanks to hoisting.
✅ Hoisted · ✅ Has own this
function expression
Function Expression
A function assigned to a variable. Not hoisted — must be defined before calling. Can be anonymous or named.
❌ Not hoisted · ✅ Has own this
arrow function
Arrow Function
Concise ES6 syntax using =>. Inherits this from the surrounding scope. Perfect for callbacks.
❌ Not hoisted · ❌ No own this
function constructor
Function Constructor
Creates a function dynamically from a string using new Function(). Rarely used — avoid in production.
⚠️ Avoid · Slow · Security risk
JavaScript — 4 Ways to Define a Function
// ── 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
JavaScript — Parameters & Return Values
// ── 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 9
Pro Tip — Return Objects
A function can only return one value — but that value can be an object or array containing multiple items. Combine this with destructuring on the calling side for clean multi-value returns: const { 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).

Function Declaration — Hoisted ✅
You can call a function declaration before it is defined in the file. JS hoists the entire function body to the top of its scope.

greet(); — works fine even though function greet() is written later in the file.
Function Expression / Arrow — Not Hoisted ❌
Variables declared with const or let are in the Temporal Dead Zone until their line is reached. Calling them before definition throws a ReferenceError.
JavaScript — Hoisting in Practice
// ── ✅ 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 line
Best Practice
Even though function declarations are hoisted, it's best practice to define functions before you use them — it makes your code easier to read top-to-bottom. Use hoisting as a mental model, not as a reason to write disorganised code.

Pure 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.

JavaScript — Pure Functions vs Side Effects
// ── ✅ 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.

Utility / Math
Wrap a reusable calculation into a named, testable function.
Validator
Returns true/false — clean and reusable across the app.
Factory / Builder
Returns a new object — avoids duplicated object literals.
Transformer
Takes data in one shape, returns it in another — pure and composable.
Guard / Validator
Early-return pattern — check edge cases at the top, main logic at the bottom.
Handler / Callback
Passed to event listeners or async functions — usually arrow functions.
JavaScript — Real-World Function Recipes
// ── 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.

Live Editor
✎ Editor
👁 Preview

Common Pitfalls & Best Practices

Avoid these common mistakes that trip up beginners and even experienced developers when working with functions.

JavaScript — Pitfalls & Best Practices
// ── ❌ 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.
Naming Convention
Name functions with verbs that describe what they do: getUser(), calculateTax(), isValid(), formatDate(). Avoid vague names like doStuff() or process(). A well-named function is self-documenting.
⚡
Free Resource
Download our JavaScript Cheat Sheet
Functions, scope, closures & arrow functions — one printable page.
Get Sheet
Quick Check
What does a function return if it has no return statement?
Quick Check
Which function type is fully hoisted and can be called before its definition?
Quick Check
What does this arrow function return? const f = name => { name };
Chapter Summary
  • A function is a reusable, named block of code. You define it once with the function keyword (or alternatives) and call it with functionName().
  • 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 return statement sends a value back to the caller and exits the function immediately. Without it, the function returns undefined.
  • 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel