Advanced Functions

Learn callbacks, closures, higher-order functions, and function patterns.

Functions are one of the most important building blocks in JavaScript. Once you understand basic functions, advanced function concepts make your code more powerful, reusable, and efficient.

Why Learn Advanced Functions?

  • Reuse code more effectively
  • Create flexible programs
  • Handle asynchronous operations
  • Organize complex logic
  • Build scalable applications

Callback Functions

javascript
function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

function sayBye() {
    console.log("Goodbye!");
}

greet("John", sayBye);

Output:

javascript
Hello John
Goodbye!

Higher-Order Functions

javascript
function performOperation(operation, a, b) {
    return operation(a, b);
}

function add(x, y) {
    return x + y;
}

console.log(performOperation(add, 5, 3));

Output:

javascript
8

Methods like map(), filter(), and reduce() are higher-order functions.

Closures

javascript
function counter() {
    let count = 0;

    return function() {
        count++;
        return count;
    };
}

const increment = counter();

console.log(increment());
console.log(increment());

Output:

javascript
1
2

Closures are useful for maintaining private data and reusable functionality.

Recursion

javascript
function countdown(number) {
    if (number === 0) {
        return;
    }

    console.log(number);

    countdown(number - 1);
}

countdown(5);

Output:

javascript
5
4
3
2
1

Immediately Invoked Function Expression

javascript
(function() {
    console.log("I run immediately!");
})();

Output:

javascript
I run immediately!

Real-World Example

javascript
function calculatePrice(price, discountFunction) {
    return discountFunction(price);
}

function applyDiscount(price) {
    return price * 0.9;
}

console.log(calculatePrice(1000, applyDiscount));

Output:

javascript
900

Summary

Advanced functions extend the power of JavaScript. Callback functions, higher-order functions, closures, recursion, and IIFEs are widely used in modern applications and prepare you for frameworks and real-world projects.

Let's learn with DevBrainBox AI