🚀 First-Class & Higher-Order Functions

1 First-Class Functions

🎯 What are First-Class Functions?

Functions that can be treated like any other value - they can be assigned to variables, passed as arguments, and returned from other functions.

Function
Variable
Pass Around
Use Anywhere
Example 1: Assigning Function to Variable
const greet = function(name) {
    return "Hello, " + name;
};

// Function stored in variable can be called
console.log(greet("Babita ji")); // Output: Hello, Babita ji

🔧 Try it yourself:

Click the button to see the output!

📚 Key Points:

  • Functions are values in JavaScript
  • Can be stored in variables
  • Can be passed as arguments
  • Can be returned from functions

H Higher-Order Functions

🚀 What are Higher-Order Functions?

Functions that either take other functions as arguments or return functions. They enable powerful programming patterns!

Function A
Higher-Order Function
Enhanced Result
Example: Function taking another function as argument
function greetUser(name, formatter) {
    return formatter(name);
}

function uppercaseName(name) {
    return name.toUpperCase();
}

// Passing function as argument
console.log(greetUser("babita ji", uppercaseName));
// Output: BABITA JI

🎮 Interactive Demo:

Choose a demo to run!

🌟 Common Higher-Order Functions:

  • map() - Transform array elements
  • filter() - Filter array elements
  • reduce() - Reduce array to single value
  • forEach() - Execute function for each element

💻 Live Examples & Practice

🎯 Example 1: Array Methods (Higher-Order Functions)

const numbers = [1, 2, 3, 4, 5];

// map() - transforms each element
const doubled = numbers.map(x => x * 2);

// filter() - filters elements based on condition
const evens = numbers.filter(x => x % 2 === 0);
Click to see array transformations!

🔥 Example 2: Function Reference vs Function Call

function sayHello() {
    return "Hello from function!";
}

// Function reference (no parentheses)
console.log(sayHello);

// Function call (with parentheses)
console.log(sayHello());
See the difference between reference and call!

⭐ Example 3: Creating a Custom Higher-Order Function

function createMultiplier(factor) {
    return function(number) {
        return number * factor;
    };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);
Create custom function generators!

🎓 Key Takeaways:

First-Class Functions: Functions are values that can be stored, passed, and returned.
Higher-Order Functions: Functions that work with other functions, enabling powerful abstractions.
Real-world usage: Array methods, event handlers, callbacks, functional programming patterns.