惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
腾讯CDC
M
MIT News - Artificial intelligence
Y
Y Combinator Blog
L
LangChain Blog
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
IT之家
IT之家
A
About on SuperTechFans
H
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Types of Functions in JavaScript
Annapoorani Kadhiravan · 2026-06-20 · via DEV Community

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:

  1. Function Declaration
  2. Function Expression
  3. Anonymous Function
  4. Arrow Function
  5. Parameters and Arguments Functions
  6. Return Function
  7. Callback Function
  8. Higher Order Function
  9. Immediately Invoked Function Expression (IIFE)
  10. Constructor Function
  11. Recursive Function
  12. 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.

  1. Order food.
  2. Wait for delivery.
  3. 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.

  1. Place the order.
  2. Wait for the restaurant to prepare it.
  3. 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/