First-Class Functions
Objectives
Explain the difference between a statement and an expression.
Use function expressions instead of function declarations and understand the differences.
Understand that functions are special objects that — among many other things — can be stored in variables and other data structures, can contain key-value pairs (properties), and can be passed to and returned from other functions.
Recognize an IIFE and break down what's going on with its unusual syntax:
(function () {})()
Introduction
Let's talk about functions. "Ugh, again?! We've already covered functions," you complain. Well, we've talked about functions before, but now it's time to really talk about functions. Bear with us, and prepare to have your mind blown.
Statements vs. expressions
Before we dive headlong into functions, let's take a minute to talk about the fundamental building blocks of JavaScript code: expressions and statements. A statement is a unit of code that accomplishes something but does not produce a value. An expression is a unit of code that produces a value.
Many of the common keywords we've encountered form statements:
Variable declarations:
const
,let
,var
Iteration:
for
,for...in
,for...of
,while
Control flow:
if...else
,switch
,break
Debugging:
debugger
All of those keywords are extremely useful, but none of them generate a value on their own. Take this if
statement:
The expression inside of the if
statement, 6 + 9
, produces a value: the number 15
. The if
statement itself, however, produces no value. We can assign the expression 6 + 9
to a variable, but we can't assign that if
statement to one:
That Unexpected token
error message is JavaScript telling us, "Hey, that keyword is for creating statements — stop trying to use it as though it's an expression!" A few more examples:
Top Tip: If you're struggling a bit with the difference between a statement and an expression, let's try thinking about it in a slightly different way. Statements can be used to hold data (const
, let
, var
), iterate over data (for
, for...in
, for...of
, while
), control the flow of data (if...else
, switch
, break
), and debug data (debugger
). Contrast that with expressions, which produce data. A JavaScript program is effectively a series of statements that control, organize, and structure a series of expressions.
If you're still having some trouble with the distinction, there's an excellent blog post by Dr. Axel Rauschmayer linked at the bottom of this lesson. But what does all of this stuff about expressions and statements have to do with functions?
Function expressions
When we first learned about functions, we learned about function declarations, which are a type of statement. That is, when we declare a function in the standard way, it does not produce a value:
However, the function
keyword is adaptable. When it's the first thing in a line of code, it forms a function declaration that creates a new function in memory but does not immediately produce a value. When it's placed anywhere except at the start of a line, it forms a function expression that creates a new function and immediately returns that function as a value:
String literals result in new strings, array literals result in new arrays, object literals result in new objects, and function expressions result in new functions:
NOTE: The parentheses surrounding the above anonymous function are so that the function
keyword isn't the first thing in the line of code. Parentheses used in this way are the grouping operator (as in 2 * (3 + 4)
), and they don't affect the value produced by the expression:
Parentheses around a function expression are only required if the function keyword would otherwise be the first thing in a line of code.
Okay, great, so we can create functions with function expressions. So what?
Functions are objects
A function can be assigned to a variable.
A function can be stored in a data structure.
A function can be the return value of another function.
A function can be passed as an argument to another function.
In a previous lesson, we told you to start thinking about functions as objects because, well, they are. A JavaScript function is simply a JavaScript object with a few added goodies. That means that everything we can do to an object can also be done to a function.
Assigning functions to variables
A function expression results in a function. Just like we can store an object in a variable, we can also store a function in a variable:
Since the result of the function expression is a function object, that variable now contains a function. What can we do to functions? We can invoke them!
Now if we wrote:
Should we expect to see 15
?? No, we'll see the definiton of the function itself. Our variables stores a reference to the function itself. We can call it whenever we want to.
Since typing myFunc
returns a function, we can invoke that function like we invoke any other function with ()
We can see 15
by typing:
Function expressions and hoisting
One thing to note when you're debating whether to use a function declaration or a function expression stored in a variable: function expressions are not hoisted. Remember, hoisting is the somewhat ill-fitting name for the process whereby the JavaScript engine stores function (and variable) declarations in memory during the compilation phase. Since they're already stored in memory by the time the execution phase starts, we can refer those 'hoisted' functions before their lexical declaration — that is, above where they're written in the code:
The above code works perfectly fine. Try it out in your browser's console. Contrastingly, function expressions are not hoisted. The JavaScript engine ignores them during the compilation phase, instead evaluating them during the execution phase. The following code will result in an error because variables declared with const
aren't hoisted:
Even if we use the dreaded var
, the variable declaration will be hoisted but the assignment — where the function is instantiated and assigned to the variable — doesn't happen until the execution phase. Therefore we see a different error, this one telling us that sayHello
is not a function:
The sayHello
variable is hoisted this time, but it contains undefined
until the assignment line is reached. We can't invoke undefined
, so sayHello()
throws an error.
Top Tip: Storing a function expression in a const
-declared variable is a good default strategy. We get all of the intelligent scoping behavior provided by const
, allowing us much more intuitive control over when and where the function is available for use.
Passing by reference
Like all JavaScript objects, functions are passed by reference. When a new function is created, it's stored at a specific location in memory. When we assign a function expression to a variable, we're not actually storing the entire function in that variable — we're simply storing a reference to the location in memory where the function lives. If we assign the value of that first variable to a new variable, the new variable also points at the same location in memory:
If we modify the function, we're changing the object in memory, so every reference to the function will see the modifications:
However, if we simply reassign the variable to a new function, it no longer points at the same location in memory:
Adding properties to a function
Since a function is just a special object, we can add properties to functions and then access them:
Storing functions in an array
We can store functions as elements in an array:
When we access the various indexes in our array, we're retrieving those stored functions:
And, one more time, what's that fun thing we can do to any function? We can invoke it! How do we invoke it? With the invocation operator:
Storing functions in objects
We can also store functions as properties of an object:
NOTE: When a function is stored in an object, we call it a method. It's also still a function, of course — methods are a subset of functions. We'll go much deeper into this in the lessons on object-oriented JavaScript, but keep the terminology in mind. A good rule of thumb: if you need to use the dot operator to invoke the function (as in ada.greet()
instead of simply greet()
), it's a method. For a common example, think of console.log()
. We're invoking the log()
method on the console
object.
Returning functions from functions
Functions can return any kind of data: strings, numbers, objects... you name it. Well, since functions are themselves merely objects, what's stopping us from returning a function from a function? Nothing! Here we create a function that assembles and returns other functions:
Then let's store the returned functions in variables so that we can reference and invoke them:
Top Tip: In a situation where we need a lot of similar but slightly different functions, this is a great pattern for cutting down on repetitive code. Instead of declaring 100 different functions, we can declare a single function and invoke it 100 times, passing in different arguments each time. We'll still end up with the same 100 functions, but we drastically reduced the amount of code we had to write.
It's turtles all the way down
There's nothing stopping us at a function that returns a function, though. How about a function that returns a function that returns a function that returns a... well, you get the idea:
When we invoke the function stored inside the howManyLicks
variable, it returns another function:
One lick down, nine more to go. When we invoke the function returned by the invocation of the first function, we get another function:
We can continue in this manner all the way down the nested functions:
Until, finally, we reach the center:
Please don't ever do this in your actual code. The deeply nested example is simply meant to familiarize ourselves with the combination of these ideas:
We can invoke functions.
Functions can return other functions.
When a function returns another function, we can invoke its return value because it's a function!
Functions passed as arguments
We already encountered this during the introduction to callback functions, but the concept is important enough to reiterate here: functions can be passed into other functions as arguments. Take a look at the following example:
The final line, hid(den)(mess)(age)
, looks super weird, but let's break it down. First, we invoke the hid()
function, and we pass the value stored in the den
variable in as the lone argument: hid(den)
. An anonymous function is stored in den
, and all hid()
does is return the passed-in argument. If we stop there, the return value of hid(den)
is the function stored in den
:
So invoking hid(den)
logs out the first message and then returns a function. The returned function accepts one argument, logs out a second message, and then returns the passed-in argument. What do we like to do with functions? Invoke 'em! Invoking hid(den)()
would do the trick, but let's also pass in another function as the fn
parameter:
And right on cue, it returns another function! This one also accepts a single argument, then logs out a message, and finally invokes the passed-in argument. If we invoke the returned function without passing an argument, we get a pretty descriptive error:
Since we didn't pass any arguments, the cb
parameter inside mess()
contained undefined
. And when the JavaScript engine hit the cb()
line inside mess()
, it yelled at us: "Hey, cb
doesn't contain a function — it contains undefined
. I can't invoke this!" When we pass in a function, such as age()
, everything works swimmingly:
Immediately-invoked function expressions
An immediately-invoked function expression (usually abbreviated to IIFE) is exactly what it says on the tin: it's a function expression that we invoke immediately. Here's a function expression that returns a function object:
What can we do with that returned function object? We can invoke it... immediately:
We can pass arguments into the invocation operator just like any old function:
We won't be using IIFEs much until we introduce closures, but it's an ubiquitous construct that you're sure to come across when searching StackOverflow and other resources.
Anonymous function expressions
We mentioned this in a previous lesson as well, but now we can put some more definite terms behind the concept. A function declaration must have a name; the JavaScript engine requires that we assign it an identifier that we can then use to refer to the function object in memory. Forgoing the name results in the following error message:
The engine is saying, "Hey, I expected to see an identifier after the function
keyword, but all I found was this silly parenthesis. That's not the start of a valid identifier!"
However, there's no such constraint on function expressions. You can add a name if you want:
But it isn't necessary:
Most of the time, an anonymous function expression will suffice. It's a bit easier to read and keeps our code less cluttered. That being said, there's one main benefit to naming your function expressions: better stack traces. This anonymous stack trace doesn't give us a lot to go on:
This one includes the function expression's name and is consequently a bit easier to locate and debug:
Conclusion
This lesson introduces a ton of new things to think about when dealing with functions in JavaScript, but you're hopefully starting to see just how powerful functions are. We'll be discussing many of these new concepts in greater depth as we continue to explore the JavaScript language. It's important that you practice and familiarize yourself with these fundamental ideas because they are the building blocks that we'll expand on and compose into increasingly complex and powerful patterns.
Resources
Last updated