![]() |
VOOZH | about |
In JavaScript, a First Class Citizen is an entity that can be assigned to a variable, passed as an argument to a function, returned from a function, and has properties and methods assigned to it.
Functions are examples of First Class Citizens in JavaScript.
Below are some terms related to First Class Citizens in JavaScript:
Table of Content
Functions in JavaScript can be treated as values, i.e. a function can be stored as a value in a variable.
Example: In this 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.
Welcome to GeeksforGeeks!
Functions in JavaScript also has the ability to be passed as arguments to another function.
Example: In this 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".
Welcome Teacher Welcome Student
Now, let's see an example of returning a function from another function in JavaScript-
Output:
Welcome to GeeksforGeeks!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.