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

推荐订阅源

B
Blog RSS Feed
博客园_首页
N
News | PayPal Newsroom
有赞技术团队
有赞技术团队
The Hacker News
The Hacker News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
S
SegmentFault 最新的问题
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
P
Privacy & Cybersecurity Law Blog
AI
AI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Schneier on Security
Schneier on Security
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
量子位
Forbes - Security
Forbes - Security
爱范儿
爱范儿
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tor Project blog
Recorded Future
Recorded Future
A
About on SuperTechFans
J
Java Code Geeks
The Register - Security
The Register - Security
PCI Perspectives
PCI Perspectives
H
Hacker News: Front Page
V2EX - 技术
V2EX - 技术
S
Secure Thoughts
V
Vulnerabilities – Threatpost
Hacker News: Ask HN
Hacker News: Ask HN
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Scott Helme
Scott Helme
T
The Exploit Database - CXSecurity.com
Y
Y Combinator Blog
AWS News Blog
AWS News Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
F
Full Disclosure
Application and Cybersecurity Blog
Application and Cybersecurity Blog
The GitHub Blog
The GitHub Blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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/