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.

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


šŸ‘„

Latest Content...

What Iā€™m up to and more.

  • 3 Reasons Why You Need to Design Components and Not Pages

    26 Jun 2021

    3 Reasons Why You Need to Design Components and Not Pages

    If you want to design better websites then you need to stop designing at a page level and start thinkning about components. Here's 3 reasons why.

  • 6 Twitter Analytics Terms You Need to Know to Grow an Audience in 2021

    26 Jun 2021

    6 Twitter Analytics Terms You Need to Know to Grow an Audience in 2021

    Building a Twitter audience is a great way to grow your business. So, here are 6 Twitter analytics terms you need to know and how to measure them.

  • The Complete 2021 Guide to HTTP Status Codes and Their SEO Influence

    1 Jun 2021

    The Complete 2021 Guide to HTTP Status Codes and Their SEO Influence

    HTTP status codes are a vital part of the web, they allow for clear communication between clients and servers as well as influence your SEO score.

Want to read more?

View all posts here