What does it mean for Functions to be "First - class - citizens / objects" in JavaScript ?

Functions belong to us!

Posted by Anas R Firdousi on March 27th, 2016
18-22 mins read

In one of my recent articles, I discussed at length how powerful are JavaScript functions and why you should get a good grip on them if you want to become a JavaScript pro. I discussed in length that Functions are objects and since objects have properties and methods, Functions can also(and do) have properties and methods. If you think you are not an expert on Call() / Apply() / Bind() methods in JavaScript or if you want a detailed refresher, I would highly encourage you to read my post on those topics before starting with this article. If you are already familiar with those concepts, this article will further help you in going Functional with JavaScript.

Quick Question : What is first-class in any programming language ?

In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, and assigned to a variable.

-Wikipedia Reference

Did you kinda get it ? Lem me explain.

Think of a variable for example:
          
    var x = 100;
          
        
What can we do with this variable?
  • I already created it which means I can create more variable like that.
  • Can we assign this variable to another variable ? Absolutely! We can!
  • Can I put this variable into an index of an array? Why not! For example, if there is an array "arr", it's easy to assign this variable to a the 5th index of "arr".
    arr[4] = x; easy!
  • Can you assign it to a property of some other object defined in your program? Let's do it:
                  
                var myObject = {
                   y:50
                };
    
                console.log(myObject); //Object {y: 50}
    
                var x = 100;
    
                myObject.x = x;
    
                console.log(myObject);
                //Object {y: 50, x: 200}
    
                  
                
  • Can you pass our variable "x" to a function? How easy is that question. Daaaaaaah!!! Yes, we can.
                  
                    var x = 100;
                    function echo(a){
                      return a;
                    }
    
                    echo(x); //100
                  
                 
  • Can you return them as values from a function? I think we all do this 100 times a day? returning a variable from a function. Do we need an example?
  • Can our variable "x" posses properties that can be dynamically assigned and created on will? Suppose "x" is an object literal this time:
                    
                var x = {};
    
                //create new properties
    
                x.newProp = null; // You do not have to assign "null", assign whatever.
    
                //assign values dynamically
                x.newProp = 100;
    
                //may be over write 100 with an object? How about that?
                x.newProp = { 
    
                  a:1, b:2
    
                }
    
                console.log(x); // Check out final state of "x" below:
    
                    
                  
Checkout the final state of "x" below:

Let's do an open heart surgery of JavaScript functions and examine them to see if we can apply all of the above operations that we did on a simple variable "x" but now on a JavaScript function. The only special feature of Function is that they can be invoked versus other objects which can not be invoked. We will discuss this in a bit.

Function Creation - The Structure

Functions in JavaScript are like any other object. Every object is a collection of key/value pairs. In JavaScript, Objects have hidden link to a prototype object. Objects created from Object literals are linked to Object.prototype. Function objects have a longer chain. Every function is linked to Function.prototype which is linked to Object.prototype.

Object object >> Object prototype
Function function >> Object object >> Object prototype

Every function object:

  • Is created with a prototype object
                        
        function SampleFunc(){  
    
        }
                        
                    

    This means that function.prototype points directly to Object.prototype:


    And if you investigate Function itself, it contains the Object.prototype methods which we just saw above as well several other properties and methods like Call/Apply/Bind which discussed in last post.



    Conclusion: Function are objects created with inherited properties & methods (coming from Object.prototype) as well as it's own set of methods(Call/Apply/Bind e.t.c) and properties(arguments, length, name e.t.c).

Assigning Function to a Variable

As you can assign an Object to a variable in JavaScript so can you assign Functions to a variable in JavaScript. This is a very powerful concept and becomes very useful when we perform things like "currying" in JavaScript. Let's try assigning a function to a variable with a simple example:

          
      function sendEmail(msg){
        console.log("Email sent with msg:" + msg) 
      }

      //Assign a function to a variable

      var emailSender = sendEmail;
      emailSender("Happy to write my first email");

      //Another useful example can be:

      //Writing "product" as a curried function, which on invocation with partial arguments
      // returns another function.
      var product = function(a){   
        return function(b){
            return a*b;
          }
      }

      var twice = product(2); // Assign a curried function to a variable

      console.log(twice(30)); //60
      console.log(twice(100)); //200


      //Twice's internal face is like:

      //var twice  =  function(b) {   return 2 * b }

          
        

With the help of JavaScript closures, "twice" is able to remember the value of "a" passed to "product" function i.e. twice is able to remember the environment in which it was created, which is within the "product" function so it is able to remember the arguments passed as well. We will discuss function returning a function in the "Returning Function from a Function" part of this post.

Functions saved in Arrays

We can save function declarations within Arrays.

        
      function crazy(){
          console.log(" Going crazy ...");
      }

      function funny(n){
          if(n <= 2){
            console.log("Just a lil funny too ...");
          }else{
            console.log("And funny!!!");
          }
      }

      var arr = [];

      arr[0] = crazy;
      arr[1] = funny;

      arr.forEach(function(v){

        if(v.length){
          v(2);
        }else{
          v();
        }

      });

      //OUTPUT:

      //Going crazy ...
      //Just a lil funny too ...

      //You can also invoke methods individually:

      arr[1](); //And funny!!!

      arr[0](); //Going crazy ...



        
      

Function as Object Property

There are many ways of defining objects and the easiest of all is Object Literals. Let's create an object literal and add some properties to it.

          
            var team = {};

            team.name = "XYZ";
            team.sports = "Soccer";
            team.results = [0,0,1,1,1,1,1,1,0,0];

            console.log(team);
            //Object {name: "XYZ", sports: "Soccer", latestResults: Array[10]}

            function getLastFiveResults(arr){
                if(arr.length<5){
                  console.log("Number of available results are less than 5");
                  return arr;
                }else{
                  return arr.slice(arr.length-5);
                }
            }


            //Dynamically adding a function to an object property
            team.getLatestResults = getLastFiveResults;

            //Let's examine the "team" object in console

          
        
We have successfully managed to add a function dynamically on the fly to a object property! We can now call the function whichever way we like:
          
            team.getLatestResults(team.results);
            //OUTPUT'
            //[1, 1, 1, 0, 0]
          
        

Function as Function / Method Arguments

As we can pass any variable to a function, we can pass any function to a function. This technique is usually used for callback functions and life cycle hooks when writing libraries. You can use it for any other purpose you like. The point of this post is we can pass functions as function arguments ( and not discuss specific use cases, that in its entirety can be a separate post).

          

            //A simple example ////////////////////////////////
            function Foo(bar){
              console.log("Running Foo...");
              bar();
            }

            function Bar(){
              console.log("Running Bar...");
            }

            Foo(Bar);

            //OUTPUT:
            Running Foo...
            Running Bar...

            //A better example ////////////////////////////////

            //Defining an object literal
            var renderer = {

              renderUI:function(){
                console.log("Rendering the UI");
              }

            }

            function createUI(renderAPI){

              console.log("Start painting screen ...");

              console.log("Start a long running task that takes 5 seconds...");
              console.log("Waiting for long running task to complete to start rendering");

              setTimeout(function() {

                  console.log("Start to render ...");
                  renderAPI();
                  console.log("Finished rendering ...");
                  console.log("Finished painting ...");

              }, 5000);

            }

            // Passing the renderer object literal function "renderUI" as argument to 
            //another function "createUI"

            createUI(renderer.renderUI); 

            //OUTPUT:
            Start painting screen ...
            Start a long running task that takes 5 seconds...
            Waiting for long running task to complete to start rendering

            (and after 5 seconds gap you will see)

            Start to render ...
            Rendering the UI
            Finished rendering ...
            Finished painting ...


          
        

Returning Function from a Function

This is an interesting topic and an entire book can be written on how powerful this is. If you have ever done functional programming in the past, you may be aware of concepts like "partial application", "currying", "composition" and the like. Returning a function from a function allows us to produce a new function by combining a function and an argument. We will only look at few basic examples here. I will discuss function returning function in great detail in upcoming posts on functional programming in JavaScript.

We have already looked at a function returning a function in the "Assigning Function to a Variable" section of this post earlier where we created a "product" function which internally returns another function. Let's start with a very basic example to understand this:

        
          
          function counter(){

            var count = 0;

            return function(){
              return count++;
            }
          }

          var count = counter();

          count(); // 0
          count(); // 1
          count(); // 2
          count(); // 3
          count(); // 4

        
      

We just wrote something called "Closure" in JavaScript. We returned an "inner" function from an "outer" function. The power here is the "inner" function (an anonymous function- a function with no name) is able to remember the a value "count" defined outside of it.
When the following statement runs:

var count = counter();
What does "count" contain ?

        function(){ 
return count++
} But it also remembers that the initial value of count( a variable defined outside of it) was "0".


You can make use of functions return a function to do anything! Folks have generally used it for doing 3 majors tasks:

To create Private variables

Following example is taken from Addy Osmani's great book JavaScript Design Pattern which is available online for free. I have taken this example where he discusses Revealing module pattern which helps you create private methods and private variables within a function.

          
            
        var myRevealingModule = (function () {
 
          var privateVar = "Ben Cherry",
              publicVar = "Hey there!";
   
          function privateFunction() {
              console.log( "Name:" + privateVar );
          }
   
          function publicSetName( strName ) {
              privateVar = strName;
          }
   
          function publicGetName() {
              privateFunction();
          }
   
   
          // Reveal public pointers to
          // private functions and properties
   
          return {
              setName: publicSetName,
              greeting: publicVar,
              getName: publicGetName
          };
 
         })();
 
        myRevealingModule.setName( "Paul Kinlan" );


          
        

Rather than returning an object as he did in above example, in some cases you may want to return a function. For example, let's write a "Notification Server" and try to keep DB information private. The consumer of the "notificationServer" will provide credentials but 'notificationServer' keeps "key" and "host" names private, hidden from the consumer.

When user creates instance of the "notificationServer" class, the constructor of the "notificationServer" returns another "inner function" which has reference to "serverAccess" variable, "connectToServer" method, "sendAlerts" method and "disconnectFromServer" method. Host and Key are kept private and never exposed to the consumer. "notificationServer" internally uses "serverAccess" class and user is unaware of that as well. Here is the code:

            
              
          function notificationServer(credential){

              //Private Members
            
              var host = "dummy.com";
              var key = "xxx666"
              var db = { 
                  user: credential.login + "@" + this.host,
                  password: credential.password,
                  key:this.key
              }

              //Public Interface of "Notification Server"

              return new (function(){
                this.serverAccess = null;
                this.connectToServer = function(){

                  this.serverAccess =  new serverAccess(db.user,db.password,db.key);

                }
                
                this.sendAlerts = function(msg){
                  if(!this.serverAccess){
                    this.connectToServer();
                    this.serverAccess.sendNotification("Test msg");
                  }
                }
                
                this.disconnectFromServer = function(){
                  this.serverAccess.disconnect();
                  this.serverAccess = null;
                }

              })

          }

          function serverAccess(userName,password,key){

            this.userName = userName;
            this.password = password;
            this.key = key;


            this.sendNotification =  function(msg){

              //May be check "key" here before sending notifications

              console.log("Sending message : " + msg);
            }

            this.disconnect = function(){
              console.log("Disconnecting from server");
              this.userName = this.password = null;
              console.log("Disconnected");
            }

          }


          //Here is the Consumer of our "notificationServer"
          // which internally uses "serverAccess".


          var credential = {
            user:"anas",
            password:"555"
          }

          var ns =  new notificationServer(credential,"abc.com");
          ns.sendAlerts();

          //Sending message : Test msg

            
          

To create Pseudo Static Members within a class

I am omitting example on how to use functions returning functions to create a static member which is shared across all instances of a class in JavaScript for the sake of keeping this article short and relevant. Find out ! ( Remember in JavaScript a function is a class itself-until ECMA5, ECMA6/ECMA2016 has a "class" construct)

One way to avoid function returning function

Let's do another version of the "product" function we wrote earlier:

   
   
      function product(a,b){   
        return a*b;    // Oh so I took off the internal function
      }

      //To partially apply arguments on the "product" function, you can use bind() function.

      var prod2 =  product.bind(null,2);

      console.log(prod2(100)); //200

   
  

Dynamic Properties on Functions

We have seen several times in this post how we can dynamically add properties to an Object literal. Can we do this on Functions ?

   
   
   function dashboardComponent(){

      this.metaData = {
        heading:"Dashboard",
        subHeading:"Data Visualizations - Last 1 year"
      }

   }

   dashboardComponent.additionalData = {
      x:100,
      y:200
   };

   dashboardComponent.prototype.additionalDataOnPrototype = {
      z:500
   };


   

Let's examine this on dev console:

In this article, we tried understanding why "Functions are first class citizens" in JavaScript. It's powerful and the best way to understand functions in JavaScript is to appreciate that they are bit different than functions in a lot of other programming languages.

Feel free to leave a comment, question, suggestion and corrections.
Until next time, Happy learning!