DevelopmentJavaScript21 Feb 2021 | 2 Min Read
JavaScript Fundamentals: First Class Functions
Functions are known as first class citizens in JavaScript, here's exactly what that means.


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.
jsx1const example = () => {2 console.log("This is an example");3};
Invoking the function by using the variable it was stored in.
jsx1example();
Passing a function as a variable
jsx1function sayName() {2 return "Coner";3}45function shout(text) {6 return text.toUpperCase();7}
We call `sayName()`
which returns 'Coner' this is then immediately passed to shout() which returns it in the upper case.
jsx1console.log(shout(sayName()));
Returing a function
If we want to invoke the function returned from another function we have a couple of options:
Option 1
jsx1const sayName = function () {2 return function () {3 console.log("Coner");4 };5};
But, directly invoking our function doesn't yeild the result we wanted.
jsx1sayName(); // Doesn't return 'Coner' instead directly returns the function.
To achieve the result we want of logging out 'Coner', we have store our function into another variable and invoke that.
jsx1const func = sayName();23func(); // 'Coner'
Option 2
jsx1const sayName = function () {2 return function () {3 console.log("Coner");4 };5};
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.
jsx1sayName()(); // 'Coner'