2. Functions (Very Important)
Functions are reusable blocks of code that perform specific tasks.
They help make code cleaner, reusable, and modular.
Topics Covered
- Function Declaration
- Function Expression
- Arrow Function
- Callback Function
- Higher-Order Function
- IIFE
- Pure Function
- Closures
1. Function Declaration
A normal function created using the function keyword.
Syntax
function functionName() {
// code
}Example
function greet() {
console.log("Hello");
}
greet();Function with Parameters
Parameters are values passed into functions.
function add(a, b) {
return a + b;
}
console.log(add(2, 3));Explanation
aandbare parameters2and3are argumentsreturnsends back result
Features
- Hoisted
- Can be called before declaration
sayHi();
function sayHi() {
console.log("Hi");
}2. Function Expression
A function stored inside a variable.
Syntax
const greet = function () {
console.log("Hello");
};Example
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(2, 4));Features
- Not fully hoisted
- Commonly used in modern JavaScript
- Can be anonymous
Difference Between Function Declaration and Function Expression
| Feature | Function Declaration | Function Expression |
|---|---|---|
| Hoisted | Yes | No |
| Syntax | Direct function | Stored in variable |
| Calling before declaration | Allowed | Not allowed |
3. Arrow Function
Short syntax introduced in ES6.
Syntax
const add = (a, b) => {
return a + b;
};Shorter Syntax
const add = (a, b) => a + b;If only one line exists, return is automatic.
Example
const square = (num) => num * num;
console.log(square(5));Difference Between Normal Function and Arrow Function
Normal Function
function greet() {
console.log("Hello");
}Arrow Function
const greet = () => {
console.log("Hello");
};Main Differences
| Feature | Normal Function | Arrow Function |
|---|---|---|
| Syntax | Longer | Short |
Own this | Yes | No |
| Constructor | Yes | No |
arguments object | Available | Not available |
this Keyword Difference (IMPORTANT)
Normal Function
const user = {
name: "Dipak",
greet: function () {
console.log(this.name);
},
};
user.greet();Output:
Dipak;Arrow Function
const user = {
name: "Dipak",
greet: () => {
console.log(this.name);
},
};
user.greet();Output:
undefined;Why?
Arrow functions do not create their own this.
They take this from parent scope.
4. Callback Function
A function passed as an argument into another function.
Example
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function done() {
console.log("Completed");
}
greet("Dipak", done);Output
Hello Dipak
CompletedWhy Callbacks are Used
- Async operations
- Event handling
- Timers
- API calls
Example with setTimeout
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);5. Higher-Order Function
A function that:
- Takes another function as parameter OR
- Returns another function
Example 1 — Function as Parameter
function operation(a, b, callback) {
return callback(a, b);
}
function add(x, y) {
return x + y;
}
console.log(operation(2, 3, add));Example 2 — Function Returning Function
function outer() {
return function inner() {
console.log("Inside inner");
};
}
const fn = outer();
fn();Common Higher-Order Functions
map()filter()reduce()forEach()
6. IIFE (Immediately Invoked Function Expression)
A function that runs immediately after creation.
Syntax
(function () {
console.log("IIFE Executed");
})();Arrow Function IIFE
(() => {
console.log("Arrow IIFE");
})();Why IIFE is Used
- Avoid global variable pollution
- Create private scope
- Execute code immediately
7. Pure Function
A function that:
- Gives same output for same input
- Does not modify external data
Example of Pure Function
function add(a, b) {
return a + b;
}Same input always gives same result.
Impure Function
let total = 0;
function add(num) {
total += num;
}This changes external variable.
Benefits of Pure Functions
- Predictable
- Easy to test
- Better debugging
- Used heavily in React
8. Closures (VERY IMPORTANT)
A closure happens when an inner function remembers variables from its outer function even after outer function execution is complete.
Basic Example
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const fn = outer();
fn();
fn();Output
1;
2;How Closures Work
Step 1
outer() runs.
let count = 0;Variable is created.
Step 2
outer() returns inner() function.
return function inner() {};Step 3
Even after outer() finishes, inner() still remembers count.
This memory behavior is called a closure.
Real-Life Analogy
Think of a closure like a backpack.
The inner function carries outer variables in its backpack even after the outer function is finished.
Why Closures are Important
Closures are heavily used in JavaScript applications.
Uses of Closures
1. Data Hiding / Private Variables
function counter() {
let count = 0;
return {
increment() {
count++;
console.log(count);
},
};
}
const c = counter();
c.increment();
c.increment();count cannot be accessed directly from outside.
2. React Hooks
Hooks like useState internally use closures.
3. Event Handlers
Closures help remember variables during events.
4. Currying
Advanced functional programming concept.
Interview Definition of Closure
A closure is created when a function remembers variables from its lexical scope even after the outer function has finished execution.
Important Interview Points
Function Declaration
- Fully hoisted
Function Expression
- Not fully hoisted
Arrow Function
- No own
this - Short syntax
- Cannot be used as constructor
Callback Function
- Function passed into another function
Higher-Order Function
- Takes or returns functions
IIFE
- Runs immediately after creation
Pure Function
- Same input → same output
- No side effects
Closure
- Inner function remembers outer variables
- Used for private variables and data persistence