JavaScript function declaration syntax: var fn = function() {} vs function fn() {}

JavaScript function declaration syntax: var fn = function() {} vs function fn() {}

In Javascript there are 2 ways to create functions:-

  1. function declaration:-
    function fn(){
      console.log("Hello");
    }
    fn();
    

    This is very basic, self-explanatory, used in many languages and standard across C family of languages. We declared a function defined it and executed it by calling it. What you should be knowing is that functions are actually objects in Javascript, internally we have created an object for above function and given it a name called fn or the reference to the object is stored in fn. Functions are objects in Javascript, an instance of function is actually an object instance.

  2. function expression:-
    var fn=function(){
      console.log("Hello");
    }
    fn();
    

    Javascript has first-class functions, that is create a function and assign it to a variable just like you create a string or number and assign it to a variable. Here, fn variable is assigned to a function. Reason for this concept is functions are objects in Javascript, fn is pointing to the object instance of the above function. We have initialized a function and assign it to a variable, its not executing the function and assigning the result.

Leave a Reply

Your email address will not be published. Required fields are marked *