Skip to main content

Functions


Function Declaration

function greet(name) {
return `Hello, ${name}!`;
}
greet("Reet"); // "Hello, Reet!"

// Function declarations are HOISTED — can call before definition
hoisted(); // works!
function hoisted() { console.log("I am hoisted!"); }

Function Expression

const add = function(a, b) {
return a + b;
};
add(3, 4); // 7

// Function expressions are NOT hoisted
notHoisted(); // TypeError: notHoisted is not a function
const notHoisted = function() { console.log("not hoisted"); };

Arrow Functions (ES6)

// Regular arrow function
const multiply = (a, b) => {
return a * b;
};

// Implicit return (single expression, no braces)
const multiply2 = (a, b) => a * b;

// Single parameter (no parens needed)
const double = n => n * 2;

// No parameters (parens required)
const sayHi = () => "Hello!";

// Return an object (wrap in parens)
const makePerson = (name, age) => ({ name, age });

// Key difference: Arrow functions do NOT have their own `this`
const obj = {
name: "Reet",
greet: function() {
console.log(this.name); // "Reet"
},
greetArrow: () => {
console.log(this.name); // undefined (arrow has no this)
}
};

Default Parameters

function greet(name = "World", greeting = "Hello") {
return `${greeting}, ${name}!`;
}

greet(); // "Hello, World!"
greet("Reet"); // "Hello, Reet!"
greet("Reet", "Hi"); // "Hi, Reet!"
greet(undefined, "Hey"); // "Hey, World!" (undefined triggers default)

Rest Parameters

function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}

sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15

// Rest must be LAST parameter
function log(level, ...messages) {
console.log(`[${level}]`, messages.join(" "));
}
log("INFO", "User", "logged", "in"); // [INFO] User logged in

Arguments Object (Regular functions only)

function showArgs() {
console.log(arguments); // array-like object
console.log(Array.from(arguments)); // convert to real array
}
showArgs(1, 2, 3); // Arguments [1, 2, 3]

// Arrow functions do NOT have arguments object

IIFE (Immediately Invoked Function Expression)

// Runs immediately after definition
(function() {
console.log("I run immediately!");
})();

// Arrow IIFE
(() => {
console.log("Arrow IIFE!");
})();

// Creates private scope
(function() {
const privateVar = "I'm private";
console.log(privateVar);
})();
// console.log(privateVar); // ReferenceError

Higher-Order Functions

A function that takes a function as argument or returns a function.

// Takes a function as argument
function applyTwice(fn, value) {
return fn(fn(value));
}
applyTwice(x => x + 3, 7); // 13

// Returns a function (closure)
function makeMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
double(5); // 10
triple(5); // 15

Pure Functions

// Pure: same input always gives same output, no side effects
function add(a, b) {
return a + b;
}

// Impure: depends on external state / has side effects
let total = 0;
function addToTotal(n) {
total += n; // side effect: modifies external variable
return total;
}

Recursion

// A function that calls itself
function factorial(n) {
if (n <= 1) return 1; // base case — ALWAYS required!
return n * factorial(n - 1); // recursive case
}
factorial(5); // 120

// Fibonacci
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
fib(10); // 55

MCQ — Functions

Q1: Which function type is hoisted?

A) Arrow functions B) Function expressions C) Function declarations ✅ D) IIFE

Answer: C

Q2: What is the output?
const fn = (x = 10) => x * 2;
console.log(fn(undefined));

A) NaN B) undefined C) 20D) 0

Answer: C — Passing undefined triggers the default value.

Q3: Arrow functions have their own this context?

A) True B) False ✅

Answer: B — Arrow functions inherit this from their enclosing lexical scope.

Q4: What is an IIFE used for?

A) Creating async functions B) Creating a private scope that executes immediately ✅ C) Declaring class methods D) Defining global variables

Answer: B

Q5: What is the arguments object?

A) An array of all parameters in any function B) An array-like object available only in regular functions (not arrow) ✅ C) A built-in property of arrow functions D) Same as rest parameters

Answer: B

Q6: Which of these is a pure function?

A) function f(n) { return n + Math.random(); } B) function f(n) { console.log(n); return n; } C) function f(a, b) { return a + b; }D) function f() { return Date.now(); }

Answer: C — Same input always gives same output with no side effects.

Q7: What is makeMultiplier(3)(7) given this code?
function makeMultiplier(factor) {
return (number) => number * factor;
}

A) 10 B) 21C) function D) NaN

Answer: BmakeMultiplier(3) returns a function. Calling it with (7) gives 3 * 7 = 21.

Q8: What is required to prevent infinite recursion?

A) A loop condition B) A base case ✅ C) A return statement at the top D) A try/catch block

Answer: B — Every recursive function must have a base case that stops the recursion.