JavaScript 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!

Key Takeaways

  • Advanced Functions is an important topic to understand.
  • Start with small examples and practice one step at a time.
  • Use the idea in simple projects so it becomes easier to remember.