30 Days Of JavaScript

Day 6: Functions Part 2

Lesson 4: Anonymous Functions

I need to introduce you to a concept that will feel out of place.

I promise it has a use that you 100%, absolutely for certain need to know about. Right this second you will think:

WTF Simon I thought we were learning useful stuff.

Functions are created with this syntax () => {} and then assigned to a storage place, with either function myCoolFunction or const myCoolFunction = we can then pass that function into another function with the myCoolFunction name.

Because function creation and storage are separate, we can create a function for one off use that has no name (hence anonymous).

Let's take the last example and convert it.

1const addNumbers = (num1, num2) => {
2  return num1 + num2;
3}
4
5const logInOut = (in1, in2, action) => {
6  console.log("in1: " + in1);
7  console.log("in2: " + in2);\n
8  const result = action(in1, in2);\n
9  console.log("result: " + result);
10  return result;
11}
12
13const converted = logInOut(10, 2, addNumbers);

We can take addNumbers and write it in the call to logInOut like this:

1const logInOut = (in1, in2, action) => {
2  console.log("in1: " + in1);
3  console.log("in2: " + in2);\n
4  const result = action(in1, in2);\n
5  console.log("result: " + result);
6  return result;
7}
8
9const converted = logInOut(10, 2, (num1, num2) => {
10  return num1 + num2;
11});

This looks horrible, so you have two options in JavaScript land. You could use the short hand arrow syntax in this case, as it is just a one line function:

1(num1, num2) => {
2  return num1 + num2;
3};

Can be written as

1(num1, num2) => return num1 + num2

Or you could just format it in an easier to read way:

1const logInOut = (in1, in2, action) => {
2  console.log("in1: " + in1);
3  console.log("in2: " + in2);\n
4  const result = action(in1, in2);\n
5  console.log("result: " + result);
6  return result;
7}
8
9const converted = logInOut(10, 2,
10    (num1, num2) => {
11      return num1 + num2;
12    }
13);

Neither is ideal, but this is one of the areas in JavaScript where we trade some niceness for lots of power.

The reason this can be conceptually difficult to "get" is that so far we have thought of our functions as things to be created and reused, a first class citizen if you will.

However later on you will learn about some very powerful functions, that require a one off function from you as part of their input.

When we get to that you will see how powerful this concept is, even if right now it's a bit mind bending as to why you would want to do this.

You wont have to wait long! The next two days are consolidation days, we will review and practice what you've learned. Then we will dive into the strange world of creating nameless functions and passing them into other functions.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co