Coner Murphy

Published on 21 Feb 2021 | 2 Minute Read

JavaScript Fundamentals: First Class Functions

Functions are known as first class citizens in JavaScript, here's exactly what that means.

Photo from Unsplash
JavaScript Fundamentals: First Class Functions

Functions are First Class Citizens

  • Meaning you can treat functions like any other variable in the language.
  • For example, you can pass a function as an argument to another function or a function can be returned by another function and assigned to a variable.

Storing a function in a variable.

1const example = () => {
2 console.log("This is an example");
3};
jsx

Invoking the function by using the variable it was stored in.

1example();
jsx

Passing a function as a variable

1function sayName() {
2 return "Coner";
3}
4
5function shout(text) {
6 return text.toUpperCase();
7}
jsx

We call `sayName()` which returns 'Coner' this is then immediately passed to shout() which returns it in the upper case.

1console.log(shout(sayName()));
jsx

Returing a function

If we want to invoke the function returned from another function we have a couple of options:

Option 1

1const sayName = function () {
2 return function () {
3 console.log("Coner");
4 };
5};
jsx

But, directly invoking our function doesn't yeild the result we wanted.

1sayName(); // Doesn't return 'Coner' instead directly returns the function.
jsx

To achieve the result we want of logging out 'Coner', we have store our function into another variable and invoke that.

1const func = sayName();
2
3func(); // 'Coner'
jsx

Option 2

1const sayName = function () {
2 return function () {
3 console.log("Coner");
4 };
5};
jsx

If we want to avoid using the variable method shown above we can use the double parentheses method to invoke the parent function and then the child function it returns which gives us the result we were after.

1sayName()(); // 'Coner'
jsx


👥