DevelopmentJavaScript | 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.
1const example = () => {2 console.log("This is an example");3};
jsxInvoking the function by using the variable it was stored in.
1example();
jsxPassing a function as a variable
1function sayName() {2 return "Coner";3}4
5function shout(text) {6 return text.toUpperCase();7}
jsxWe call `sayName()`
which returns 'Coner' this is then immediately passed to shout() which returns it in the upper case.
1console.log(shout(sayName()));
jsxReturing 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};
jsxBut, directly invoking our function doesn't yeild the result we wanted.
1sayName(); // Doesn't return 'Coner' instead directly returns the function.
jsxTo 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'
jsxOption 2
1const sayName = function () {2 return function () {3 console.log("Coner");4 };5};
jsxIf 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