Understanding First-Class Functions in JavaScript
Aris Zagakos
Posted on March 12, 2021
Table of Contents
Introduction
JavaScript is a programming language with First-class Functions.
A programming language is said to have First-class Functions when functions in that language are treated like any other variable. For example, in such a language, a function can be assigned as a value to a variable, can be passed as an argument to other functions and can be returned by another function.
Assign a function to a variable
// Assign an Anonymous Function to a variable
const greeting = () => {
console.log('Hi Mikaela!');
};
// Invoke the function using the variable
greeting();
Pass a function as an argument
const sayHi = () => {
return 'Hi ';
};
const greeting = (hiFn, name) => {
console.log(hiFn() + name);
};
// Pass `sayHi` as an argument to `greeting` function
greeting(sayHi, 'Mikaela!');
Return a function
const greeting = () => {
return () => {
console.log("Hi Mikaela!");
};
};
// invoke the inner function
greeting()();
// or
var hi = greeting();
hi();
Let's try another example
Create a function that is called addTwoNumbers. This function takes one number as parameter and it returns another function that takes again one number as parameter and finally returns the sum of these two numbers.
function addTwoNumbers(num1) {
return (num2) => {
return num1 + num2;
};
};
// Invoke the function
const add = addTwoNumbers(10);
// 15
console.log(add(5));
Conclusion
First-class functions are a very important part of the JavaScript ecosystem, using them you can work on powerful design patterns such as higher-order functions, partial function application, callbacks, and much more.
Resources
Posted on March 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024
November 22, 2024