June 13, 2016
It is important to understand both of these paradigms to truly master the language. We’ve discussed inheritance in some depth before in the article above. In this post we will discuss how first class functions work in the language.
In this post we will cover the basics before moving on to real world applications of the paradigm in future posts.
Let’s get started.
First Class functions – Lets define them:
In short, a language that supports first class functions is a language where a function has all the properties of or can inherit all of the other properties found within the language.
So, for example, with first class functions, you can:
- Assign functions to variables.
- Pass functions around like variables.
- Create functions on the fly.
Everything you can do with other types like objects, strings, booleans, can all be done with functions.
You should think of a function as an object, where your code is just a single attribute of that function, but certainly that is certainly not the only attribute your function has.
See the diagram below:
As you can see, we have our function object in the center. This function, being an object, is capable of having primitives such as strings, numbers and booleans, other functions, and other objects assigned to that function.
Here is an example, let’s start with the very basic function
Woah! Cool right? Bet you have not seen that before.
Here I am actually using the function’s object properties, totally independent of it’s code properties.
We just added a property to a function. In other programming languages, this simply would not be possible.
As you can see, when I
console.log the value ‘english’ prints to the screen.
A function has a name property.
A function has code
So, in addition to all of the properties an object would typically have, a function has code you write that you can execute. This is the code found inside the function. As a day to day programmer, this is the feature of functions you are most familiar with.
You write a function, take arguments and modify that state of those arguments in some way before returning the code.
Making a function first class gives it a TON of features
Stay tuned for more on this subject!