Functions : first class objects

Interview Questions

Functions are first-class objects in JS. They possess all the capabilities of objects and are thus treated like any other object in the language. So, we can say that functions are first-class objects.

They can be:

  • Created via literals
    1
    2
    3
    
    function ninjaFunction() {
      // something happens here
    }
    
  • Assigns a new function to a variable
    1
    2
    3
    
    var ninjaFunction = function() {
      // something happens here
    }; 
    
  • Adds a new function to an array
    1
    2
    3
    
    ninjaArray.push(function(){
      // something happens here
    }); 
    
  • Assigns a new function as a property of another object
    1
    2
    3
    
    ninja.data = function(){
      // something happens here
    };
    
  • Passed as arguments to other functions
    1
    2
    3
    4
    
    function call(ninjaFunction){ 
      ninjaFunction();
    } 
    call(function(){});
    
  • Returned as values from functions
    1
    2
    3
    
    function returnNewNinjaFunction() { 
      return function(){}; 
    }
    
  • They can possess properties that can be dynamically created and assigned:
    1
    2
    3
    4
    
    var ninjaFunction = function(){
      // something happens here
    }; 
    ninjaFunction.name = "Hanzo";
    

Whatever we can do with objects, we can do with functions as well. Functions are objects, just with an additional, special capability of being invokable:

Functions can be called or invoked in order to perform an action.

Interview questions

Q1. What do you mean by first class objects in JavaScript?