Contents
Different Types of Functions in JavaScript
Functions are one of the most important building blocks in JavaScript. They allow you to group code together and reuse it throughout your program.
In JavaScript, there are several ways to define functions — each with unique behavior and use cases.
Function Declaration
A function declaration (also known as a named function) is the traditional way to define a function.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
- Starts with the
functionkeyword. - Can be called before it’s defined (due to hoisting).
- Has its own scope and
thiscontext.
Example of Hoisting:
sayHello(); // Works!
function sayHello() {
console.log("Hello, World!");
}
Function Expression
In a function expression, a function is stored inside a variable.
const add = function(a, b) {
return a + b;
};
console.log(add(3, 5)); // Output: 8
- The function has no name (it’s anonymous) unless you give it one.
- It’s not hoisted — you must define it before calling it.
- Useful when passing functions as arguments or assigning them dynamically.
Arrow Function (ES6)
Introduced in ES6, arrow functions provide a shorter syntax and behave differently with the this keyword.
const multiply = (a, b) => a * b;
console.log(multiply(4, 6)); // Output: 24
- No need for the
functionkeyword. - Implicit return if there’s only one expression.
- Does not have its own
this— inherits from the parent scope. - Commonly used for callbacks and array methods.
Example:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
Anonymous Functions
An anonymous function is a function without a name — often used as an argument to another function.
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
- No name — only used where it’s defined.
- Common in event handlers, callbacks, and higher-order functions.
Immediately Invoked Function Expression (IIFE)
An IIFE is a function that runs immediately after it’s defined.
(function() {
console.log("I run instantly!");
})();
- Defined and executed at once.
- Creates a private scope — variables inside it can’t be accessed outside.
- Useful for avoiding global variable pollution.
Higher-Order Functions
A higher-order function is any function that takes another function as an argument or returns a function.
function higherOrder(fn) {
fn();
}
higherOrder(() => console.log("Hello from higher-order function!"));
- Foundation of functional programming.
- Examples:
.map(),.filter(),.reduce(), and event listeners.
Callback Functions
A callback function is a function passed as an argument to another function and executed later.
function fetchData(callback) {
setTimeout(() => {
callback("Data received!");
}, 1000);
}
fetchData((message) => console.log(message));
// Output: Data received! (after 1 second)
- Used for asynchronous operations like API calls, timers, etc.
- Can be replaced by Promises or async/await for better readability.
Constructor Functions
A constructor function is used to create objects (before classes were introduced).
function Person(name, age) {
this.name = name;
this.age = age;
}
const user = new Person("Alice", 25);
console.log(user.name); // Output: Alice
- Used with the
newkeyword. thisrefers to the new object being created.- Forms the foundation for JavaScript’s prototypal inheritance.
Generator Functions (ES6)
A generator function allows you to pause and resume execution using the yield keyword.
function* counter() {
yield 1;
yield 2;
yield 3;
}
const count = counter();
console.log(count.next().value); // 1
console.log(count.next().value); // 2
- Declared with
function*. - Returns an iterator.
- Useful for lazy evaluation and managing async tasks.
Async Functions (ES8)
Async functions make working with Promises easier by using async and await.
async function getData() {
const data = await fetch("https://api.example.com/data");
return data.json();
}
- Always return a Promise.
- Use
awaitto pause until a Promise resolves. - Makes asynchronous code look synchronous and clean.
Summary
| Type | Syntax | Hoisted | this Behavior | Common Use |
|---|---|---|---|---|
| Function Declaration | function greet() {} | ✅ Yes | Own this | Reusable functions |
| Function Expression | const fn = function(){} | ❌ No | Own this | Dynamic assignment |
| Arrow Function | const fn = () => {} | ❌ No | Lexical this | Callbacks, array methods |
| IIFE | (function(){})() | ❌ No | Own this | Private scope |
| Async Function | async function(){} | ✅ Yes | Own this | Asynchronous operations |
| Generator | function* gen(){} | ❌ No | Own this | Iterators |
| Constructor | function Person(){} | ✅ Yes | New object this | Object creation |