Understanding JavaScript Function As First-class Citizen

This is a short post explaining the meaning of JavaScript function as a first-class citizen.

We often hear the phrase "Function is a first-class citizen in JavaScript", but what exactly does it mean?

It means that JavaScript function possesses all the capabilities of JavaScript object and is thus treated like any other object in the language. And to be specific:

  1. Function can be created with literals.
    function() {}
    
  2. Function can be assigned to variables, array entries, and properties of other objects.
    const exampleFunction = function() {}; // assigns to a variable
    exampleArray.push(function() {}); // adds to an array
    example.data = function() {}; // assigns as a property of another object
    
  3. Function can be passed as an argument to another function.
    function call(exampleFunction {
     exampleFunction();
    }
    call(function() {})
    
  4. Function can be returned from another function.
    function exampleFunction() {
     return function() {};
    }
    
  5. Function can be assigned properties.
    const exampleFunction = function() {};
    exampleFunction.name = "Example";
    

Whatever we can do with object in JavaScript, we can also do with function. Function is the same as object, but with an additional, special capability of being invokable. That is, function can be called or invoked in order to perform an action.