Skip to content

First-Class Values

In JavaScript, functions are "first-class values" which means we can use them like any other data type. We can assign them to variables, pass them as arguments, and return them from other functions.

Assigning Functions

Functions can be assigned to variables:

js
function sayHello() {
    return "Hello, ";
}
const saySomething = sayHello;    // Assign the function itself
const result = sayHello();        // Call the function and assign its result
console.log(saySomething());      // "Hello, "
console.log(result);              // "Hello, "

Functions as Arguments

Functions can be passed to other functions:

js
function greeting(msg, name) {
    return msg() + name;
}

// We can pass different functions to change behavior
function sayHello() {
    return "Hello, ";
}
function sayHi() {
    return "Hi, ";
}

console.log(greeting(sayHello, "Sam"));  // Hello, Sam
console.log(greeting(sayHi, "Sam"));     // Hi, Sam

Returning Functions

Functions can return other functions:

js
function makeGreeting(greeting) {
    // Return a customized greeting function
    return function(name) {
        return greeting + " " + name;
    };
}

// Create different greeting functions
const greetHello = makeGreeting("Hello");
const greetHi = makeGreeting("Hi");

console.log(greetHello("Sam"));  // Hello Sam
console.log(greetHi("Sam"));     // Hi Sam

Callbacks

A common use of first-class functions is callbacks, especially in event handling:

js
function handleClick() {
    console.log("Button was clicked!");
}

// Pass the function as a callback
button.addEventListener("click", handleClick);

// Or use an arrow function directly
button.addEventListener("click", () => {
    console.log("Button was clicked!");
});

The event listener doesn't call our function right away. Instead, it saves the function and calls it later when the event occurs. This is why we pass the function itself (handleClick) and not its result (handleClick()).

💡 The callback pattern is fundamental to event handling and asynchronous code, which we'll explore more when working with user interfaces.