4.8 Functions Functions are reusable blocks of code that perform a specific task. Instead of writing the same code repeatedly, we can place it inside a function and call it whenever needed.
What is a Function? A function is a block of code designed to perform a particular task. Example: function greet() {
console.log("Hello");
} Calling the function: greet(); Output: Hello
Why Use Functions? Functions provide: ✓ Code Reusability ✓ Better Organization ✓ Easier Maintenance ✓ Reduced Duplication Without functions: console.log("Welcome"); console.log("Welcome"); console.log("Welcome"); With functions: function welcome() {
console.log("Welcome");
}
welcome(); welcome(); welcome();
Function Declaration The most common way to create a function.
Syntax function functionName() {
// code
}
Example function greet() {
console.log("Hello World");
} Calling: greet(); Output: Hello World
Function with Return Value function add() {
return 10 + 5;
}
Example const result = add();
console.log(result); Output: 15
Function Expression A function stored inside a variable.
Syntax const variableName = function() {
};
Example const greet = function() {
console.log("Hello");
}; Calling: greet(); Output: Hello
Function Declaration vs Function Expression Function Declaration function greet() {
}
Function Expression const greet = function() {
};
Difference Function declarations are hoisted. greet();
function greet() {
console.log("Hello");
} Works.
Function expressions are not fully hoisted. greet();
const greet = function() {
}; Output: ReferenceError
Parameters Parameters allow functions to receive data.
Syntax function greet(name) {
} Here: name ↓ Parameter
Example function greet(name) {
console.log(
"Hello " + name
);
} Calling: greet("Samir"); Output: Hello Samir
Multiple Parameters function add(a, b) {
return a + b;
} Calling: add(10, 20); Output: 30
Arguments vs Parameters function greet(name) {
} name ↓ Parameter
greet("Samir"); "Samir" ↓ Argument
Default Parameters Default parameters provide fallback values.
Syntax function greet(name = "Guest") {
}
Example function greet(name = "Guest") {
console.log(
`Hello ${name}`
);
}
Calling: greet(); Output: Hello Guest
Calling: greet("Samir"); Output: Hello Samir
Multiple Default Parameters function createUser(
name = "Guest",
age = 18
) {
console.log(name, age);
}
Rest Parameters Rest parameters collect multiple values into an array.
Syntax function test(...values) {
}
Example function sum(...numbers) {
console.log(numbers);
} Calling: sum(1, 2, 3, 4); Output: [1, 2, 3, 4]
Real Example function add(...numbers) {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
} Calling: add(10, 20, 30); Output: 60
Rest Parameter Rules Only one rest parameter is allowed.
Correct: function test(a, b, ...rest) {
}
Incorrect: function test(...a, ...b) {
}
Arrow Functions Introduced in ES6. Shorter syntax for writing functions.
Traditional Function function greet() {
console.log("Hello");
}
Arrow Function const greet = () => {
console.log("Hello");
};
Arrow Function with Parameters const greet = (name) => {
console.log(
`Hello ${name}`
);
};
Calling: greet("Samir"); Output: Hello Samir
Arrow Function Returning Value Traditional: function add(a, b) {
return a + b;
}
Arrow: const add = (a, b) => {
return a + b;
};
Short Form const add = (a, b) => a + b;
Calling: add(10, 20); Output: 30
Single Parameter Shortcut Instead of: const square = (x) => {
return x * x;
}; Use: const square = x => x * x;
Arrow Functions and this Arrow functions do not have their own: this They inherit it from the surrounding scope.
Traditional: function test() {
console.log(this);
}
Arrow: const test = () => {
console.log(this);
}; Behavior differs. (Detailed coverage in the this topic.)
IIFE IIFE stands for: Immediately Invoked Function Expression A function that executes immediately after creation.
Syntax (function() {
console.log("Hello");
})(); Output: Hello
Arrow IIFE (() => {
console.log("Hello");
})(); Output: Hello
Why Use IIFE? Creates a private scope.
Example (function() {
const secret = "123";
console.log(secret);
})(); Output: 123
Outside: console.log(secret); Output: ReferenceError
Recursion Recursion occurs when a function calls itself.
Basic Example function countdown(n) {
console.log(n);
countdown(n - 1);
} Problem: Infinite Recursion
Base Case Every recursive function needs a stopping condition.
Example function countdown(n) {
if (n === 0) {
return;
}
console.log(n);
countdown(n - 1);
} Calling: countdown(5); Output: 5 4 3 2 1
How Recursion Works countdown(3)
↓ countdown(2)
↓ countdown(1)
↓ countdown(0)
↓ Stop
Factorial Example Mathematical Formula: 5! = 5 × 4 × 3 × 2 × 1
Recursive Solution function factorial(n) {
if (n === 1) {
return 1;
}
return n *
factorial(n - 1);
} Calling: factorial(5); Output: 120
Recursive Visualization factorial(5)
5 × factorial(4)
5 × 4 × factorial(3)
5 × 4 × 3 × factorial(2)
5 × 4 × 3 × 2 × factorial(1)
5 × 4 × 3 × 2 × 1
120
Function Scope Variables inside functions are local.
Example function test() {
const message = "Hello";
} Outside: console.log(message); Output: ReferenceError
Returning Values Functions can send values back using return.
Example function multiply(a, b) {
return a * b;
} Calling: const result = multiply(5, 4); Output: 20
Complete Example const calculateTotal = ( price, quantity = 1 ) => {
return price * quantity;
};
console.log( calculateTotal(100, 3) ); Output: 300
Function Types Summary Type Example Function Declaration function greet(){} Function Expression const greet = function(){} Arrow Function const greet = () => {} IIFE (function(){})() Recursive Function Function calling itself
Best Practices Use Descriptive Names Good: function calculateTotal() {
} Bad: function x() {
}
Prefer Arrow Functions for Small Functions const add = (a, b) => a + b;
Use Default Parameters function greet( name = "Guest" ) {
}
Always Return When Needed function add(a, b) {
return a + b;
}
Always Include Base Case in Recursion if (n === 0) {
return;
}
Summary Concept Purpose Function Declaration Standard function Function Expression Function stored in variable Parameters Input values Arguments Values passed to function Default Parameters Fallback values Rest Parameters Collect multiple arguments Arrow Functions Short ES6 functions IIFE Execute immediately Recursion Function calling itself Return Send value back
Key Takeaway Functions are reusable blocks of code that make programs modular and maintainable. Function Declaration ↓ Standard Functions
Arrow Functions ↓ Modern Functions
Rest Parameters ↓ Unlimited Arguments
IIFE ↓ Immediate Execution
Recursion ↓ Function Calls Itself Functions are one of the most important concepts in JavaScript because React components, event handlers, API calls, hooks, and application logic are all built using functions.