DEV Community

Zakaria EL AISSAOUI
Zakaria EL AISSAOUI

Posted on • Edited on

JavaScript: First-class Functions

Javascript is a programming language that allows functions to be treated as variables, known as First-class functions. This means that a function can be passed as an argument to other functions, returned by another function, and assigned as a value to a variable.

Passing a function as an argument

One example of passing a function as an argument is seen in the function executeOperation, which takes in a handler function, and a and b as arguments. The handler function (in this case sum) is then executed with a and b as its arguments and the result is logged.

Passing a function as an argument


Returning a function

Another example is seen in the function addToValue, which returns a new function that takes in another value and adds it to the original value passed in. This returned function is then assigned to a variable addTo3 and can be called with a new value.

Returning a function


Assigning a function to a variable

Lastly, a function can also be assigned to a variable as seen in the example of predicate, which takes in a value and returns a boolean based on whether the value is equal to 3.

Assigning a function to a variable

It's worth noting that functions that take other functions as arguments or return functions are known as higher-order functions.

Top comments (0)