JavaScript
Functions
Functions are reusable blocks of code. They take inputs (parameters), execute logic, and optionally return an output. In JavaScript, functions are first-class values — you can store them in variables, pass them as arguments, and return them from other functions.
// ── 1. Function Declaration (hoisted — can call before definition) ──
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Rahul")); // "Hello, Rahul!"
// ── 2. Function Expression (stored in a variable) ──────────────────
const add = function(a, b) {
return a + b;
};
console.log(add(3, 5)); // 8
// ── 3. Arrow Function (modern, concise) ────────────────────────────
const multiply = (a, b) => a * b; // implicit return
const square = n => n * n; // single param: no parens
const sayHi = () => console.log("Hi"); // no params: empty parens
// Arrow with body (explicit return required)
const getDiscount = (price, pct) => {
const discount = price * (pct / 100);
return price - discount;
};
// ── Default Parameters ──────────────────────────────────────────────
function createUser(name, role = "viewer") {
return { name, role }; // shorthand for { name: name, role: role }
}
console.log(createUser("Ananya")); // { name: "Ananya", role: "viewer" }
console.log(createUser("Admin", "admin")); // { name: "Admin", role: "admin" }
// ── Rest Parameters (collect args into array) ───────────────────────
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
// ── Higher-order functions (functions as arguments) ─────────────────
const nums = [1, 2, 3, 4, 5];
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]
const evens = nums.filter(n => n % 2 === 0);// [2, 4]
const total = nums.reduce((acc, n) => acc + n, 0); // 15
💡
Arrow functions don't have their own this. They inherit this from their surrounding scope — this makes them ideal for callbacks inside class methods and event handlers where you need to preserve the outer this.