First class function in JavaScript

JavaScript treats functions as first-class citizens, meaning they can be stored in variables, passed as arguments, and returned from other functions. This powerful feature enables functional programming patterns and higher-order functions.

What are First-Class Functions?

In JavaScript, functions are first-class objects, which means they have all the capabilities of other objects. They can be:

  • Stored in variables and data structures
  • Passed as arguments to other functions
  • Returned as values from functions
  • Assigned properties and methods

Storing Functions in Variables

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First-Class Functions</title>
</head>
<body>
<script>
// Store function in variable
const greet = function(name) {
    return `Hello, ${name}!`;
};

// Store arrow function in variable
const multiply = (a, b) => a * b;

console.log(greet("Alice"));
console.log(multiply(4, 5));
</script>
</body>
</html>
Hello, Alice!
20

Functions as Parameters (Higher-Order Functions)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Functions as Parameters</title>
</head>
<body>
<script>
// Function that accepts another function as parameter
function processArray(arr, callback) {
    const result = [];
    for (let item of arr) {
        result.push(callback(item));
    }
    return result;
}

// Functions to pass as callbacks
const double = x => x * 2;
const square = x => x * x;

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

console.log("Original:", numbers);
console.log("Doubled:", processArray(numbers, double));
console.log("Squared:", processArray(numbers, square));
</script>
</body>
</html>
Original: [1, 2, 3, 4, 5]
Doubled: [2, 4, 6, 8, 10]
Squared: [1, 4, 9, 16, 25]

Functions Returning Functions

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Functions Returning Functions</title>
</head>
<body>
<script>
// Function that returns another function
function createMultiplier(multiplier) {
    return function(number) {
        return number * multiplier;
    };
}

// Create specific multiplier functions
const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log("Double 10:", double(10));
console.log("Triple 7:", triple(7));

// Using closures to create counters
function createCounter() {
    let count = 0;
    return function() {
        return ++count;
    };
}

const counter1 = createCounter();
const counter2 = createCounter();

console.log("Counter 1:", counter1()); // 1
console.log("Counter 1:", counter1()); // 2
console.log("Counter 2:", counter2()); // 1
</script>
</body>
</html>
Double 10: 20
Triple 7: 21
Counter 1: 1
Counter 1: 2
Counter 2: 1

Practical Example: Event Handling

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First-Class Functions Demo</title>
<style>
body {
    font-family: Arial, sans-serif;
    padding: 20px;
}
.result {
    font-size: 18px;
    font-weight: bold;
    color: #e74c3c;
    margin: 10px 0;
}
button {
    padding: 10px 20px;
    margin: 5px;
    font-size: 16px;
}
</style>
</head>
<body>
<h2>Array Transformation Example</h2>
<p>Original array: [2, 4, 6, 8]</p>
<div class="result" id="result">Click a button to transform the array</div>
<button onclick="transformArray(double)">Double Numbers</button>
<button onclick="transformArray(square)">Square Numbers</button>
<button onclick="transformArray(increment)">Add One</button>

<script>
const originalArray = [2, 4, 6, 8];

// Functions that can be passed as arguments
const double = x => x * 2;
const square = x => x * x;
const increment = x => x + 1;

// Higher-order function that accepts a function parameter
function transformArray(transformFunction) {
    const result = originalArray.map(transformFunction);
    document.getElementById('result').textContent = 
        `Transformed array: [${result.join(', ')}]`;
}
</script>
</body>
</html>

Built-in Higher-Order Functions

JavaScript provides many built-in methods that demonstrate first-class functions:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Built-in Higher-Order Functions</title>
</head>
<body>
<script>
const numbers = [1, 2, 3, 4, 5, 6];

// map() - transforms each element
const doubled = numbers.map(x => x * 2);
console.log("Doubled:", doubled);

// filter() - selects elements based on condition
const evenNumbers = numbers.filter(x => x % 2 === 0);
console.log("Even numbers:", evenNumbers);

// reduce() - combines all elements into single value
const sum = numbers.reduce((acc, x) => acc + x, 0);
console.log("Sum:", sum);

// forEach() - executes function for each element
console.log("Numbers:");
numbers.forEach(x => console.log(`  ${x}`));
</script>
</body>
</html>
Doubled: [2, 4, 6, 8, 10, 12]
Even numbers: [2, 4, 6]
Sum: 21
Numbers:
  1
  2
  3
  4
  5
  6

Conclusion

First-class functions make JavaScript incredibly powerful for functional programming. They enable clean, reusable code through higher-order functions and provide the foundation for many JavaScript patterns and frameworks.

Updated on: 2026-03-15T23:18:59+05:30

742 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements