Functions are weird. Consider the following code:
Seems straightforward enough, right? We’re creating a function
sayHello, then immediately calling it.
Now, what about the following code:
This “intuitive” code comes loaded with assumptions and processes that we regularly take for granted:
- Why are we able to assign a function to a variable?
- What is this doing under the hood?
- Are we able to utilize functions in potentially unexpected ways?
For example, do you know what “function currying” is and why it’s useful? Or do you know how
.filter are implemented?
Fret not, dear reader, as we will now take a look at all these questions.
Why are we able to assign a function to a variable?
To understand why we’re able to assign a function to a variable, let’s analyze what happens when anything is assigned to a variable.
How memory works
Inside of your computer, there’s something called “memory,” AKA RAM,which allows your computer to store short-term memory that it can quickly reference later.
When we create a variable, what we’re doing is storing values inside of this memory.
For example, take the following code:
This will create two sections of memory that your compiler will keep around for reference when you use those variables. Each of these sections of memory will be just big enough to store 5 characters of the string.
This might be visually represented like so:
It’s important to remember that the memory address itself doesn’t store the name, your compiler does. When you create blocks of memory via variables, the compiler gets back a number that it can use to look up the variable’s value inside of a “stack” of memory.
You can loosely think of this memory stack as an array that the compiler looks through in order to get the data based on an index. This number can be huge because your computer likely has multiple gigabytes of RAM. Even 16GB is equivalent to 1.28e+11 bytes. Because of this, memory addresses are often colloquially shortened to hexadecimal representations.
This means that our 0x7de35306 memory address is associated with bit number 2112049926, or just over the 0.2GB mark.
This explanation of memory is a very generalized explanation of how memory allocation works. You can read more about memory stacks here.
When your browser compiles the following code:
The browser’s compiler will replace the variable names with memory addresses:
This code is simply pseudocode and will not actually run. Instead, your computer will compile down to “machine code” or “assembly code”, which will in turn run on “bare metal”. What’s more, this is a drastic oversimplification of how your browser’s JIT compiler and your system’s memory managementactually works under-the-hood.
How does this relate to function storage?
Is roughly equivalent to:
As you might correctly assume, this means that both of these syntaxes allow a function to be stored in memory.
Using our pseudocode again, this might look like:
Why does it matter that functions are stored as memory addresses?
Without having to assign each number to a variable:
Likewise, you can use functions without assigning them to a variable.
This means the the following
Can be used without a variable to assign the function:
This is just the start of what’s possible with functions. Think of all the interactions you can have with a non-function variable like integers and strings. You can have those same interactions with functions as well.
Can you pass a function to another function?
One very popular use of functions is passing in values as properties. For example:
Here, we’re passing a string as a property to the
Just like you can pass in integers, strings, or arrays to a function, you might be surprised to know you can also pass in functions into a function:
This will output the same “Hello” as our previous
Not only can you call these functions that are passed as parameters, but you can pass parameters to those functions as well.
To walk through this step-by-step, we:
callThisFnthrough an argument
callThisFnassigns that property as
callback, which remains a function
- We then call
callbackwith a parameter of it’s own: ‘Hello, world’
In case this isn’t clear, let’s do our previous trick of calling a function without assigning it to a variable.
What about returning a function from another function?
As a function’s input, parameters are only half of the story of any function’s capabilities – just as any function can output a regular variable, they can also output another function:
getMessage and storing the return value to
message variable. We can then do anything else we might expect with this
message variable – including passing it to other functions as a parameter.
This too, is possible with a function as a return value:
This code block is an extension on the “returned value” idea. Here, we’re returninganother function from
getMessageFn. This function is then assigned to
messageFn which we can then in turn call itself.
Funnily enough, you can even combine this with the ability to return within the inner function.
Let’s combine concepts by accepting and returning a function from another function
Knowing that we can both accept a function as a property and return a different function as a value, we can combine these both to create the following logic:
How do you pass data from one function to another? A pipe function!
The concepts we’ve spoken about today are commonly utilized when programming in a style called “functional programming.” Functional programming is a style of programming – similar to“Object Oriented Programming” (OOP) – that utilizes functions as a method to pass, change, and structure data.
Functional programming relies heavily on the properties of functions that we’ve looked at today: passing functions to other functions, returning functions from functions, and more.
pipe function takes a list of other functions to call them and return a final value.
For example, you might run:
This is useful when you need to chain a list of actions together and get the final output.
pipe is an easy function to implement:
So when is this useful? Let’s assume that we want to clamp the values between two numbers.
Thinking about this problem, we can break up our logic into three different parts:
- Check if smaller than minimum
- Check if larger than maximum
- Return final value
We can implement this using distinct functions and our new
While this might seem a bit confusing at first, the benefits are that we now are able to use the
max method independently of
For example, want to run a function over each item of an array?
Array.forEach to the rescue!
Array.forEach doesn’t just pass a single value to the inner mapping function, it also passes the index of the item and the original array:
Mapping items in an array to a new value
Don’t have a use for “
forEach“? No matter! There’s also
Array.map that enables you to have a list and want to change each item in the list in some way.
Array.map accepts a function that, when you return a new value, will update that item of the list.
Array.map passes the index of the item and the original array to the inner function as well:
Filter a list down based on a function’s return value
Say that you have a list of numbers:
And want to filter down this list to only include “small” numbers – aka when a number is smaller than 50. This is where we can use
Once again, you’re also given the option to get the index and original array in the filter method.
Reduce an array down to a single value
While there are other array methods, the last one we’ll be taking a look at today enables you to reduce a list down to a single value. Let’s take a list of numbers and sum them together to a final output.
Reduce is passed two items:
- The function that provides a reduced value when returned
- The initial value to set to
For example, a
forEach can be implemented using a basic
Similarly, you can write your own implementation of
map with an intermediary array alongside a
filter is as easy as adding a single
if statement to our
reduce is similar to our
map implementation, but instead of
pushing new values to an array, we simply replace the old value between loop iterations.
Functional programming methods can be applied everywhere
The functional programming paradigms we’ve touched on today are immensely popular in ecosystems like React applications and library development. In particular, React uses these concepts alongside its
If you find any of these techniques useful (or even confusing, we know that functional programming can be a world of its own) let us know on Twitter!