If any programming language has the ability to treat functions as values, to pass them as arguments and to return a function from another function then it is said that programming language has First Class Functions and the functions are called as First Class Citizens in that programming language.
Functions are very important and powerful in JavaScript. JavaScript has all those abilities or features that are required to be a language having First Class Functions, hence functions are treated as First Class Citizens. Let’s look at all the abilities of functions being a First Class Citizen.
1. Ability to treat functions as values: Functions in JavaScript can be treated as values, i.e. a function can be stored as a value in a variable.
Javascript
<script> var greet = function () { console.log( "Welcome to neveropen!" ); } greet(); </script> |
Output:
Welcome to neveropen!
In the above example, a function is stored in a variable greet, and the variable with parenthesis, i.e. greet() calls the body of the function and shows the output in the console. Anonymous function is used in the places where that function is used as a value.
2. Ability to pass a function as arguments: Functions in JavaScript also has the ability to be passed as arguments to another function. Let’s see an example-
Javascript
<script> function teacher(){ return "Teacher" ; } function student(){ return "Student" ; } function greet(user){ console.log( "Welcome" , user()); } // Prints "Welcome Teacher" var message = greet(teacher); // Prints "Welcome Student" var message = greet(student); </script> |
Output:
Welcome Teacher Welcome Student
In the above example, when we pass the argument in function greet() as teacher, it passes the body of function teacher() and returns the string “Teacher” but when we pass the argument in function greet() as student, it passes the body of function student() and returns the string “Student”.
3. Ability to return a function from another function: Now, let’s see an example of returning a function from another function in JavaScript-
Javascript
<script> var greet = function (){ return function (){ console.log( "Welcome to neveropen!" ); } } greet()(); </script> |
Output:
Welcome to neveropen!
Here, we use the double parentheses to invoke the returned function, hence we use greet()(). Single parenthesis will call the function itself without invoking its returned function. We can also do it by storing the function in a variable like this-
var func = greet(); func();
Functions that return a function are called Higher Order Functions.
As we can see JavaScript has all the required abilities and features to be a programming language having First Class Functions and hence the functions in JavaScript are called as First Class Citizens.