In JavaScript, functions are considered to be first-class citizens, meaning they are treated as values and can be assigned to variables, passed as arguments to other functions, and returned as values from functions.
A first-class function is a function that can be treated like any other value in the language. This means that you can pass a function as an argument to another function, return a function as a value from a function, and assign a function to a variable.
For example, consider the following code:
function square(x) {
return x * x;
}
var f = square;
console.log(f(4)); // outputs 16
In this code, the square
function is assigned to the variable f
. f
is now a reference to the square
function, and it can be called just like any other function.
Another example of using first-class functions is the map
function in JavaScript. The map
function takes a function as an argument and applies that function to each element of an array, returning a new array with the results. Here's an example:
var numbers = [1, 2, 3, 4];
var squares = numbers.map(function(x) {
return x * x;
});
console.log(squares); // outputs [1, 4, 9, 16]
In this code, the map
function takes an anonymous function as an argument, which returns the square of each element in the numbers
array. The map
function then returns a new array (squares
) with the results of applying the function to each element in the original array.