JavaScript Functions
Learn how to write reusable blocks of code, use arrow functions, pass parameters, and write clean, bug-free functions.
1. What is a Function?
A function is simply a reusable block of code designed to do one specific job. Instead of writing the same 10 lines of code every time you need to calculate a total price, you write it once inside a function and run it whenever you need it.
💡 Think of a function like a kitchen recipe
You give it ingredients (called parameters), it follows steps inside, and gives you back a finished dish (called the return value).
Standard Function (Classic)
Created using the function keyword. JavaScript loads it into memory early so you can call it anywhere.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alex")); // "Hello, Alex!"
Arrow Function (Modern ⚡)
Shorter, modern way to write functions using the => arrow. Great for quick calculations.
const add = (a, b) => a + b;
const square = n => n * n;
console.log(add(5, 3)); // 8
console.log(square(4)); // 16
2. Default Values & Collecting Extra Inputs (`...rest`)
You can set fallback values in case someone forgets to pass an input, or collect any number of inputs into a list:
// 1. Default Parameters: Used if no value is passed in
function welcomeUser(name = "Guest", role = "Viewer") {
return `Welcome ${name}! Your role is: ${role}`;
}
console.log(welcomeUser()); // "Welcome Guest! Your role is: Viewer"
console.log(welcomeUser("Anshuman", "Admin")); // "Welcome Anshuman! Your role is: Admin"
// 2. Rest Parameters (...numbers): Collects all remaining inputs into a list
function calculateTotal(...prices) {
// prices is a normal array: [10, 20, 30]
return prices.reduce((sum, p) => sum + p, 0);
}
console.log(calculateTotal(10, 20, 30, 40)); // 100
Welcome Guest! Your role is: Viewer Welcome Anshuman! Your role is: Admin 100
3. Pure vs Impure Functions (Avoiding Side Effects)
A big secret to writing bug-free code is writing pure functions:
Pure Function (Like a Calculator ✅)
If you give it 2 + 2, it always gives you 4. It does not touch or mess with anything outside itself.
function calculateTax(price, taxRate) {
return price + (price * taxRate);
}
// Predictable & easy to test!
Impure Function (Modifies Outside State ⚠️)
Changes variables that live outside the function, or uses random values.
let cartTotal = 0;
function addToCart(itemPrice) {
cartTotal += itemPrice; // Changes external variable!
return cartTotal;
}
4. Recursion: Functions That Call Themselves
A recursive function is simply a function that calls itself until it reaches a stopping point (called the base case).
💡 Think of Russian Nesting Dolls
You open a doll to find a smaller doll inside. You keep opening dolls until you find the tiniest solid doll in the center (the stopping point), and then you're done!
// Example: Factorial (5! = 5 * 4 * 3 * 2 * 1)
function factorial(n) {
// 1. Stopping point (Base Case)
if (n <= 1) return 1;
// 2. Call itself with a smaller number
return n * factorial(n - 1);
}
console.log("5! is:", factorial(5)); // 120
5! is: 120
5. IIFE (Functions That Run Immediately)
An IIFE (Immediately Invoked Function Expression) is a function that runs automatically as soon as it is written. It is used to keep secret variables safe inside its own room:
const secretVault = (function() {
// This variable is private and locked inside
const secretCode = "SECRET_KEY_123";
return {
unlock(code) {
return code === secretCode ? "Door Opened!" : "Access Denied!";
}
};
})();
console.log(secretVault.unlock("SECRET_KEY_123")); // "Door Opened!"
// console.log(secretCode); // ❌ Error! secretCode is protected inside
Door Opened!
6. Function Types at a Glance
| Type | How it looks | Best Used For |
|---|---|---|
| Function Declaration | function doWork() {} |
Standard reusable functions you want available everywhere in your file |
| Arrow Function | const doWork = () => {} |
Short, modern one-liners and callbacks inside array methods |
| IIFE | (function() {})() |
Running setup code immediately while hiding private variables |
7. Functions Interview Deck
Test your knowledge on function hoisting, arrow function characteristics, call-time default parameters, and pure functions:
8. Practice Challenge
🎯 Coding Challenge: Functions & Rest Parameters
1. Write a function calculateStats(...numbers) using rest parameters that returns an object containing the sum, avg, max, and min.
2. Write a recursive function countdown(n) that counts down by numbers separated with a space until it stops with "Done!" when n <= 0.