JavaScript Guide
Beginner14 minsJS Tutorial

JavaScript Functions

Master JavaScript functions — declarations, expressions, arrow functions, parameters, return values, scope, and real-world usage patterns.

Lesson session

0% complete

0/5
Learn mode

Read the concept first, then inspect syntax and examples.

Study prompt

Current mode guidance

Read the concept first, then inspect syntax and examples.

Confidence

Track your comfort

55%
NewClear

Quick notes

0/240 characters

Concept switcher

Move through the idea before the code.

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.

Example preview

Run it in your head

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;
Output

Predict the output first, then reveal it.

Next useful links

Related pages from the same JavaScript guide.

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. ReadabilitycalculateGST(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

javascript
// ═══════════════════════════════════════════════
// 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
Reference API Specifications
Parameters:
  • 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
Return Value:

Functions return undefined by default. Use the return keyword to send back any value — number, string, object, array, boolean, or another function.

Syntax Explanation:

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 stack

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

javascript
// 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;
expected console output
180 180 180 Hello World
Breakdown:

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.

javascript
// 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" }));
expected console output
Asha Sharma { name: 'Ravi', role: 'user', verified: false, createdAt: '2026-06-01' } { name: 'Priya', role: 'admin', verified: true, createdAt: '2026-06-01' } 4446 Mira <mira@example.com> [guest]
Breakdown:

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.

javascript
// 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));
expected console output
Doubled: [200, 400, 600] Squared: [10000, 40000, 90000] With tax: [118, 236, 354] Triple 5: 15 10x of 7: 70
Breakdown:

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.

javascript
// ─── 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"));
expected console output
true false ₹12,34,567.89 This is a very long product... 01 Jun 2026
Breakdown:

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 addEventListener callback is a function — button.addEventListener('click', handleSubmit) where handleSubmit is 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

1

Exercise Challenge

Write a function calculateOrderTotal(items) that takes an array of {price, qty} objects and returns the total with 18% GST.

2

Exercise Challenge

Write a createCounter(start, step) function that uses closure to track and increment a counter.

Practice Tasks Checklist

1Write a function `isEven(n)` that returns true if n is even, false otherwise.
2Write a function `capitalize(str)` that capitalizes the first letter of each word.
3Write a function `calculateBMI(weightKg, heightM)` that returns the BMI category (Underweight/Normal/Overweight/Obese).
4Write a function `filterByPrice(products, min, max)` that returns products in a price range.
5Write a function `createGreeter(language)` that returns a greeting function for that language (closure).
6Rewrite 5 repetitive code blocks in a file as a single reusable function.
7Write a function `debounce(fn, delay)` — calls fn only if delay ms have passed since last call.
8Write `pipe(...fns)` that chains functions: pipe(double, addTax)(100) first doubles then adds tax.
9Create a `memoize(fn)` function that caches results for the same inputs.
10Write unit tests (manual console.assert) for a function you've written.

JavaScript Functions Quiz Challenges

1

Quiz Challenge

What does a function return if it has no return statement?

2

Quiz Challenge

What is the difference between a function declaration and a function expression regarding hoisting?

3

Quiz Challenge

What is the correct way to pass a function as an argument to setTimeout?

4

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.

Related Lessons

Frequently Asked Questions