⬅ Previous Topic
Working with File Paths - Relative vs AbsoluteNext Topic ⮕
Map, Filter, Reduce⬅ Previous Topic
Working with File Paths - Relative vs AbsoluteNext Topic ⮕
Map, Filter, ReduceIn programming, a language is said to have first-class functions if functions are treated like any other variable. This means you can:
This concept is a fundamental building block of functional programming.
First-class functions give us the power to abstract and encapsulate logic in ways that improve flexibility and readability. They're the foundation of common patterns like:
function greet() {
print("Hello, world!")
}
sayHello = greet
sayHello() // Calling the function using the new variable
Hello, world!
We defined a function greet
and then assigned it to a new variable sayHello
. Because functions are first-class citizens, sayHello()
executes the same logic.
function execute(callback) {
callback()
}
function showMessage() {
print("This is a callback function.")
}
execute(showMessage)
This is a callback function.
Why would you want to pass a function as an argument?
Answer: To customize the behavior of a function without rewriting its code. This is useful in situations like event handling or asynchronous operations.
function outerFunction() {
function innerFunction() {
print("Returned from outer function")
}
return innerFunction
}
returnedFunc = outerFunction()
returnedFunc()
Returned from outer function
The outerFunction
creates and returns innerFunction
. When we assign it to returnedFunc
, we can call it like any regular function.
function add(a, b) {
return a + b
}
function subtract(a, b) {
return a - b
}
operations = {
"sum": add,
"diff": subtract
}
print(operations["sum"](5, 3))
print(operations["diff"](5, 3))
8 2
What’s the benefit of storing functions in a data structure?
Answer: It allows for dynamic execution based on keys or logic, making your code more flexible and modular.
First-class functions allow us to write cleaner, more abstract, and modular code. They enable techniques like callbacks, higher-order functions, and dynamic function execution — all of which are critical in both functional and modern event-driven programming.
⬅ Previous Topic
Working with File Paths - Relative vs AbsoluteNext Topic ⮕
Map, Filter, ReduceYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.