Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 625
Kishore Kumar Korada Avatar asked Nov 28 '25 15:11

Kishore Kumar Korada


2 Answers

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.

like image 141
Bergi Avatar answered Nov 30 '25 03:11

Bergi


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;
like image 22
An0nC0d3r Avatar answered Nov 30 '25 05:11

An0nC0d3r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!