Open In App

What is First Class Citizen in JavaScript?

Last Updated : 19 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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.

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.

JavaScript
let greet = function () {
    console.log("Welcome to GeeksforGeeks!");
}
greet();

Output
Welcome to GeeksforGeeks!

Ability to pass a function as arguments

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”.

JavaScript
function teacher(){
    return "Teacher";
}

function student(){
    return "Student";
}

function greet(user){
    console.log("Welcome", user());    
}

// Prints "Welcome Teacher"
let message = greet(teacher);

// Prints "Welcome Student" 
let message1 = greet(student);

Output
Welcome Teacher
Welcome Student

Ability to return a function from another function

Now, let’s see an example of returning a function from another function in JavaScript-

JavaScript
let greet = function () {
    return function () {
        console.log("Welcome to GeeksforGeeks!");
    }
}
greet()();

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.



Next Article

Similar Reads