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();
Enter fullscreen mode Exit fullscreen mode
Output:
Tea is ready
Enter fullscreen mode Exit fullscreen mode
Why Do We Need Functions?
Without functions:
console.log("Welcome");
console.log("Welcome");
console.log("Welcome");
Enter fullscreen mode Exit fullscreen mode
With functions:
function welcome() {
console.log("Welcome");
}
welcome();
welcome();
welcome();
Enter fullscreen mode Exit fullscreen mode
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();
Enter fullscreen mode Exit fullscreen mode
Output:
Hello World
Enter fullscreen mode Exit fullscreen mode
Real-Time Example
Think of a recipe book.
Whenever you want tea, you follow the recipe.
function makeTea() {
console.log("Tea is ready");
}
makeTea();
Enter fullscreen mode Exit fullscreen mode
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();
Enter fullscreen mode Exit fullscreen mode
Output:
Hello World
Enter fullscreen mode Exit fullscreen mode
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");
};
Enter fullscreen mode Exit fullscreen mode
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();
Enter fullscreen mode Exit fullscreen mode
Output:
Anonymous Function
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
4. Arrow Function
Introduced in ES6.
Syntax
Traditional Function:
function add(a, b) {
return a + b;
}
Enter fullscreen mode Exit fullscreen mode
Arrow Function:
const add = (a, b) => {
return a + b;
};
Enter fullscreen mode Exit fullscreen mode
Or shorter:
const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode
Output:
add(10,5)
Enter fullscreen mode Exit fullscreen mode
15
Enter fullscreen mode Exit fullscreen mode
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");
Enter fullscreen mode Exit fullscreen mode
Output:
Hello John
Enter fullscreen mode Exit fullscreen mode
Real-Life Example
Ordering pizza.
orderPizza("Cheese");
Enter fullscreen mode Exit fullscreen mode
Here:
- Parameter = pizza type
- Argument = Cheese
Another example:
function multiply(a, b) {
console.log(a * b);
}
multiply(5,4);
Enter fullscreen mode Exit fullscreen mode
Output:
20
Enter fullscreen mode Exit fullscreen mode
6. Return Function
Returns a value to the caller.
function add(a, b) {
return a + b;
}
let result = add(10,20);
console.log(result);
Enter fullscreen mode Exit fullscreen mode
Output:
30
Enter fullscreen mode Exit fullscreen mode
Real-Life Example
ATM Machine
Input:
Withdraw ₹5000
Enter fullscreen mode Exit fullscreen mode
Output:
Cash ₹5000
Enter fullscreen mode Exit fullscreen mode
The cash returned is similar to the return statement.
Without return:
function add(a,b){
console.log(a+b);
}
Enter fullscreen mode Exit fullscreen mode
With return:
function add(a,b){
return a+b;
}
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
Output:
Hello John
Good Bye
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
Output:
Learning JavaScript
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
Output:
[2,4,6]
Enter fullscreen mode Exit fullscreen mode
filter()
let nums = [10,20,30,40];
let result = nums.filter(function(num){
return num > 20;
});
console.log(result);
Enter fullscreen mode Exit fullscreen mode
Output:
[30,40]
Enter fullscreen mode Exit fullscreen mode
9. IIFE (Immediately Invoked Function Expression)
Runs immediately after creation.
(function() {
console.log("Executed Immediately");
})();
Enter fullscreen mode Exit fullscreen mode
Output:
Executed Immediately
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
Output:
{
name: "John",
age: 21
}
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
11. Recursive Function
A function calling itself.
function countDown(n) {
if(n === 0)
return;
console.log(n);
countDown(n-1);
}
countDown(5);
Enter fullscreen mode Exit fullscreen mode
Output:
5
4
3
2
1
Enter fullscreen mode Exit fullscreen mode
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));
Enter fullscreen mode Exit fullscreen mode
Output:
120
Enter fullscreen mode Exit fullscreen mode
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());
Enter fullscreen mode Exit fullscreen mode
Output:
{ value:1, done:false }
{ value:2, done:false }
{ value:3, done:false }
Enter fullscreen mode Exit fullscreen mode
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);
Enter fullscreen mode Exit fullscreen mode
Output
Data fetched successfully
Enter fullscreen mode Exit fullscreen mode
Using await
async function getUser() {
let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
let data = await response.json();
console.log(data);
}
getUser();
Enter fullscreen mode Exit fullscreen mode
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));
Enter fullscreen mode Exit fullscreen mode
Output
15
Enter fullscreen mode Exit fullscreen mode
Real-Time Example
Think of a company.
Company
↓
Department
↓
Employees
Enter fullscreen mode Exit fullscreen mode
Similarly:
Outer Function
↓
Inner Function
Enter fullscreen mode Exit fullscreen mode
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();
Enter fullscreen mode Exit fullscreen mode
Output
John
Enter fullscreen mode Exit fullscreen mode
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));
Enter fullscreen mode Exit fullscreen mode
Output
8
Enter fullscreen mode Exit fullscreen mode
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++;
}
Enter fullscreen mode Exit fullscreen mode
Here, the global variable changes, so this is an Impure Function.
Pure Function Example
function increment(num) {
return num + 1;
}
console.log(increment(5));
Enter fullscreen mode Exit fullscreen mode
Output
6
Enter fullscreen mode Exit fullscreen mode
Real-Time Example
Think of a calculator.
2 + 3 = 5
Enter fullscreen mode Exit fullscreen mode
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));
Enter fullscreen mode Exit fullscreen mode
Output
100
Enter fullscreen mode Exit fullscreen mode
Another Example
function displayNames(...names) {
console.log(names);
}
displayNames("John", "David", "Sam");
Enter fullscreen mode Exit fullscreen mode
Output
["John", "David", "Sam"]
Enter fullscreen mode Exit fullscreen mode
Real-Time Example
Think of a shopping basket.
Sometimes you buy:
1 item
Enter fullscreen mode Exit fullscreen mode
Sometimes:
5 items
Enter fullscreen mode Exit fullscreen mode
Sometimes:
20 items
Enter fullscreen mode Exit fullscreen mode
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 FunctionsReferences
https://www.geeksforgeeks.org/javascript/functions-in-javascript/
답글 남기기