Skip to content
BENIBIX Learn

First-Class Function

Development🧭 Programming ParadigmsFunctional Programming

Also known as First-Class Functions, Functions as Values, First-Class Citizen

A function treated as a value. You can store it, pass it or return it.

Think of it like

It is like a recipe card you can hand around. You can keep it, pass it on or give it back.

Example

A button takes a function to run when clicked. Lucy passes in her save function, and the button calls it later.

Why it matters

It lets you pass actions around like data. Sort rules, click handlers and retries all rely on it.

Definition

A language has first-class functions when a function is treated like any other value. You can store one in a variable. You can pass one into another function, and a function can hand one back. JavaScript, Python and Kotlin all work this way. It is what makes callbacks and higher-order functions possible.

Example code

python
def shout(text):
    return text.upper()

say = shout
print(say("hi"))
# HI
The function is stored in a new name, then called through it.
One function, used three ways: stored, passed in and handed back.

Common mistake

Adding brackets when passing a function, like save(). That runs it at once and passes its answer instead.

Key takeaways

  1. 1
    Store it. Put a function in a variable.
  2. 2
    Pass it. Give it to another function.
  3. 3
    Return it. A function can make one.

Compare