Print Shortlink

Function Statements and Expressions in JavaScript

JavaScript is not really taken very seriously as a programming language, when it has to be. This statement comes to my mind whenever I read the book JavaScript, Good Parts.

In JavaScript you can define a function as a statement or as an expression.ie.,

   function eat(){ document.write("Eating"); }//Statement
   var eat = function(){ document.write("Eating"); }//Expression

The main difference between the two comes in the use of the function. A function declared as a statement can be used anywhere in the script ie., even before the declaration like

      eat();//prints Eating
      function eat(){ document.write("Eating"); }//Statement

The same code will throw an error if the function were declared as an expression.

      eat();//Uncaught TypeError: Property 'eat' of object [object DOMWindow] is not a function
      var eat = function(){ document.write("Eating"); }//Statement

So we’ll have to either stick to using functions as statements or expressions in the code. Need to be careful when we use both.

Page 1 of 1

2 Responses

  1. Nitya

    When would we go for the 2nd one? 1st one would always be preferred…isn’t it?

  2. Prabhu

    You would choose the ‘expression’ form when you actually start writing Object Oriented JavaScript ie., when you start treating the functions as Objects.

Leave a Reply