Functions are one of the most important concepts in JavaScript. They help us organize code, avoid repetition, and make programs easier to understand and maintain.
Think of a function as a machine:
- You give it some input.
- It performs a task.
- It may return an output.
For example:
function makeTea() {
console.log("Tea is ready");
}
makeTea();
Output:
Tea is ready
Why Do We Need Functions?
Without functions:
console.log("Welcome");
console.log("Welcome");
console.log("Welcome");
With functions:
function welcome() {
console.log("Welcome");
}
welcome();
welcome();
welcome();
Real-Life Example
Imagine a washing machine.
- Put clothes inside (input).
- Start the machine (function).
- Get clean clothes (output).
Similarly, a JavaScript function takes data, processes it, and gives a result.
Types of Functions in JavaScript
There are several types of functions:
- Function Declaration
- Function Expression
- Anonymous Function
- Arrow Function
- Parameters and Arguments Functions
- Return Function
- Callback Function
- Higher Order Function
- Immediately Invoked Function Expression (IIFE)
- Constructor Function
- Recursive Function
- Generator Function
1. Function Declaration
Also called Named Function.
Syntax
function greet() {
console.log("Hello World");
}
greet();
Output:
Hello World
Real-Time Example
Think of a recipe book.
Whenever you want tea, you follow the recipe.
function makeTea() {
console.log("Tea is ready");
}
makeTea();
Characteristics
✔ Has a name
✔ Can be called multiple times
✔ Supports hoisting
2. Function Expression
A function stored inside a variable.
Syntax
const greet = function() {
console.log("Hello World");
};
greet();
Output:
Hello World
Real-Time Example
Saving a contact in your phone.
Instead of remembering the number, you store it with a name.
const add = function() {
console.log("Addition");
};
Here:
- Variable = contact name
- Function = phone number
Characteristics
✔ Stored in variables
✔ No hoisting like function declarations
✔ Useful when passing functions around
3. Anonymous Function
A function without a name.
const display = function() {
console.log("Anonymous Function");
};
display();
Output:
Anonymous Function
Real-Life Example
Temporary workers in a company.
They perform a task but don't have permanent identities.
Similarly, anonymous functions are often used once and then discarded.
Example with setTimeout()
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);
4. Arrow Function
Introduced in ES6.
Syntax
Traditional Function:
function add(a, b) {
return a + b;
}
Arrow Function:
const add = (a, b) => {
return a + b;
};
Or shorter:
const add = (a, b) => a + b;
Output:
add(10,5)
15
Real-Life Example
Traditional function is like writing a full letter.
Arrow function is like sending a WhatsApp message—short and quick.
Characteristics
✔ Short syntax
✔ Common in React
✔ Doesn't have its own this
5. Functions with Parameters and Arguments
Parameters receive values.
Arguments are the actual values passed.
function greet(name) {
console.log("Hello " + name);
}
greet("John");
Output:
Hello John
Real-Life Example
Ordering pizza.
orderPizza("Cheese");
Here:
- Parameter = pizza type
- Argument = Cheese
Another example:
function multiply(a, b) {
console.log(a * b);
}
multiply(5,4);
Output:
20
6. Return Function
Returns a value to the caller.
function add(a, b) {
return a + b;
}
let result = add(10,20);
console.log(result);
Output:
30
Real-Life Example
ATM Machine
Input:
Withdraw ₹5000
Output:
Cash ₹5000
The cash returned is similar to the return statement.
Without return:
function add(a,b){
console.log(a+b);
}
With return:
function add(a,b){
return a+b;
}
The returned value can be reused later.
7. Callback Function
A function passed as an argument to another function.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Good Bye");
}
greet("John", sayBye);
Output:
Hello John
Good Bye
Real-Life Example
Food delivery.
- Order food.
- Wait for delivery.
- Delivery boy calls you.
The call after delivery is like a callback.
Another example:
setTimeout(function() {
console.log("Executed after 3 seconds");
}, 3000);
8. Higher Order Function
Functions that:
- Receive another function.
- Return another function.
Example:
function operation(callback) {
callback();
}
function display() {
console.log("Learning JavaScript");
}
operation(display);
Output:
Learning JavaScript
Real-Life Example
A manager assigning work to employees.
- Manager = Higher Order Function
- Employees = Callback Functions
Examples:
map()
let numbers = [1,2,3];
let result = numbers.map(function(num){
return num * 2;
});
console.log(result);
Output:
[2,4,6]
filter()
let nums = [10,20,30,40];
let result = nums.filter(function(num){
return num > 20;
});
console.log(result);
Output:
[30,40]
9. IIFE (Immediately Invoked Function Expression)
Runs immediately after creation.
(function() {
console.log("Executed Immediately");
})();
Output:
Executed Immediately
Real-Life Example
Automatic doors.
As soon as someone approaches, the door opens automatically.
Similarly, IIFE executes instantly.
Used for:
- Initialization
- Avoiding variable conflicts
10. Constructor Function
Used to create objects.
function Student(name, age) {
this.name = name;
this.age = age;
}
let s1 = new Student("John", 21);
console.log(s1);
Output:
{
name: "John",
age: 21
}
Real-Life Example
Cookie cutter.
One mold creates many cookies.
Similarly, one constructor creates many objects.
let s2 = new Student("David", 22);
let s3 = new Student("Sam", 23);
11. Recursive Function
A function calling itself.
function countDown(n) {
if(n === 0)
return;
console.log(n);
countDown(n-1);
}
countDown(5);
Output:
5
4
3
2
1
Real-Life Example
Russian dolls.
Each doll contains another smaller doll until the last one.
Factorial Example
function factorial(n) {
if(n === 1)
return 1;
return n * factorial(n-1);
}
console.log(factorial(5));
Output:
120
12. Generator Function
Introduced in ES6.
Creates values one by one.
function* numbers() {
yield 1;
yield 2;
yield 3;
}
let num = numbers();
console.log(num.next());
console.log(num.next());
console.log(num.next());
Output:
{ value:1, done:false }
{ value:2, done:false }
{ value:3, done:false }
Real-Life Example
Netflix episodes.
Episodes are loaded one at a time instead of loading the entire series at once.
13. Async Function
An Async Function is used to perform asynchronous operations like API calls, database queries, or file handling.
It always returns a Promise and allows us to use the await keyword.
Syntax
async function fetchData() {
return "Data fetched successfully";
}
fetchData().then(console.log);
Output
Data fetched successfully
Using await
async function getUser() {
let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
let data = await response.json();
console.log(data);
}
getUser();
Real-Time Example
Imagine ordering food through Swiggy or Zomato.
- Place the order.
- Wait for the restaurant to prepare it.
- Receive the food when it is ready.
The waiting process is similar to an async function.
Where is it used?
- API calls
- Database operations
- File uploads
- AWS services
- Fetch requests
14. Nested Function
A function defined inside another function is called a Nested Function.
Inner functions can access variables from the outer function.
Example
function outerFunction(a) {
function innerFunction(b) {
return a + b;
}
return innerFunction;
}
const addTen = outerFunction(10);
console.log(addTen(5));
Output
15
Real-Time Example
Think of a company.
Company
↓
Department
↓
Employees
Similarly:
Outer Function
↓
Inner Function
The employee (inner function) can access resources provided by the department (outer function).
Another Example
function parent() {
let name = "John";
function child() {
console.log(name);
}
child();
}
parent();
Output
John
15. Pure Function
A Pure Function always produces the same output for the same input and does not modify external data.
Example
function add(a, b) {
return a + b;
}
console.log(add(5,3));
Output
8
Why is it called Pure?
Because:
✔ Same input → Same output
✔ No side effects
✔ Doesn't change global variables
Impure Function Example
let count = 0;
function increment() {
count++;
}
Here, the global variable changes, so this is an Impure Function.
Pure Function Example
function increment(num) {
return num + 1;
}
console.log(increment(5));
Output
6
Real-Time Example
Think of a calculator.
2 + 3 = 5
No matter how many times you perform the calculation, the answer will always be 5.
That's exactly how pure functions work.
Advantages
- Predictable
- Easy to test
- Easier debugging
- Commonly used in React and Functional Programming
16. Rest Parameter Function
Rest parameters (...) allow a function to accept any number of arguments.
Syntax
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(10,20,30,40));
Output
100
Another Example
function displayNames(...names) {
console.log(names);
}
displayNames("John", "David", "Sam");
Output
["John", "David", "Sam"]
Real-Time Example
Think of a shopping basket.
Sometimes you buy:
1 item
Sometimes:
5 items
Sometimes:
20 items
The basket can hold any number of items.
Similarly, Rest Parameters allow a function to receive any number of arguments.
Complete List of JavaScript Function Types
| No | Function Type |
|---|---|
| 1 | Function Declaration (Named Function) |
| 2 | Function Expression |
| 3 | Anonymous Function |
| 4 | Arrow Function |
| 5 | Parameter and Argument Functions |
| 6 | Return Functions |
| 7 | Callback Functions |
| 8 | Higher Order Functions |
| 9 | IIFE (Immediately Invoked Function Expression) |
| 10 | Constructor Functions |
| 11 | Recursive Functions |
| 12 | Generator Functions |
| 13 | Async Functions |
| 14 | Nested Functions |
| 15 | Pure Functions |
| 16 | Rest Parameter Functions |
References
https://www.geeksforgeeks.org/javascript/functions-in-javascript/
Top comments (0)