JS Questions: What is a First-Class Function?

This is the fifth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is a First-Class Function?

In JavaScript, functions can be assigned to variables, passed as arguments to other functions, returned by functions, and stored in data structures. Basically, functions are instances of JavaScript’s Object type, just like strings or arrays.

Below is an example of a JavaScript arrow function being assigned a variable name, exclaim. JavaScript’s map function is called on an array of words, and passes in the exclaim function as an argument. These are two ways first-class functions can be used.

When a function takes in another function as an argument and/or returns a function as its value, it is known as a higher-order function. The map example above is a higher-order function.

A function passed as an argument to another function is known as a callback function.

Not all programming languages have first-class functions. With Ruby, for example, methods cannot be assigned to variables or be passed to other methods.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s