can i ask why sometimes we create a function, we end up with a semi colon and sometimes does not
function test(){
};
function test(){
}
can i ask why sometimes we create a function, we end up with a semi colon and sometimes does not
function test(){
};
function test(){
}
Depends on how you declare the function.
var myfunc = function() {}; // use semicolon
function myfunc() {} // don't use semicolon
check compress following code in http://javascriptcompressor.com/
var test = function (){
}
a = 10;
its like var test=function(){}a=10;
, which is SyntaxError
it will not be a problem for declare function like
function test(){
}
compress code function test(){}a=10;
is valid one
To contextualize the answer, you have two scenarios to deal with.
Function declaration - explicitly declaring a function thus:
function someFunction(){
// some code
}
Function Expression - declaring the function as an expression thus:
var someFunction = function(){
// some code
};
NOTE You only need semicolon in the second case. The difference is important when it comes to the concept of function hoisting.
Function hoisting basically means that you have to put into consideration at what point you want your function to be 'visible' (execution context) at run time. Case 1 enables the function to be visible anywhere within the script to mean irrespective of where you have declared the function within the script, you can always call it. The function is hoisted higher up in the execution context. On the other hand, this does not happen for case 2, so you can only call the function below the line where you have declared it.