Kishore Kumar Korada
Kishore Kumar Korada

Reputation: 1264

should or shouldn't we use semicolon after a function declaration inside a main function in Javascript?

I've come across multiple examples and I'm getting confused about placing semicolon after declaring a function where it acts as a function inside function as shown in the below example

var myFunction = function() {
   var value = "parentValue";   

   function otherFunction() {
      var value = "childValue";
      console.log("Value is : "+value);
   }

   otherFunction();
}

myFunction();

i.e placing the semicolon in the end of the otherFunction() declaration. If I keep ; or not it's working. So which is the best practice?

Upvotes: 2

Views: 138

Answers (2)

An0nC0d3r
An0nC0d3r

Reputation: 1303

Note that the assignment of the anonymous function to myFunction needs a semi colon, no other statement in this scenario is required...

   var myFunction = function() 
   {
       var value = "parentValue"; // declaring a var so use semicolon

       function otherFunction() 
       {
          var value = "childValue"; // declaring a var so use semicolon
          console.log("Value is : "+value)
       } // is not being assigned to anything so no need for semicolon

       otherFunction()

    }; // declaring a var so use semicolon

    myFunction()

And to give an idea how this would work with the module pattern...

var Module = (function(){

    var value = "parentValue";

    function _myFunction()
    {
        _otherFunction()
    } 

    function _otherFunction() 
    {
        var value = "childValue";
        console.log("Value is : "+value)
    }

    return{

        myFunction: _myFunction()
    }; // with semicolon

})(); // with semicolon

Module.myFunction;

Upvotes: 4

Bergi
Bergi

Reputation: 664195

Function declarations are no statements. They are not terminated by a semicolon, you should not use any.

If you put a semicolon there, it's parsed as an empty statement after the declaration.

However, not all function definitions are statements. myFunction is a variable that is assigned a function expression, and assignments are expression (or variable declaration) statements that are (should be) terminated by a semicolon.

function otherFunction() {
    …
} // <-- no semicolon after declaration

var myFunction = function() {
    …
}; // <-- semicolon after assignment

See also var functionName = function() {} vs function functionName() {} for more differences.

Upvotes: 6

Related Questions