Which is the best way to define a function?

Is there a difference between the two? I used both methods, but I don’t know what to do, and which is better?

function abc(){ // Code comes here. } abc = function (){ // Code comes here. } 

Is there a difference between defining these functions? Something like i ++ and ++ i?

+6
source share
2 answers
 function abc(){ // Code comes here. } 

Will be raised.

 abc = function (){ // Code comes here. } 

Will not be raised.

For example, if you did this:

  abc(); function abc() { } 

The code will run while abc is raised at the top of the scope.

If you, however, have done:

  abc(); var abc = function() { } 

abc declared, but does not matter and therefore cannot be used.

Regarding what, the programming style is best discussed.

http://www.sitepoint.com/back-to-basics-javascript-hoisting/

+7
source

The short answer is no.

You put this function in the global namespace. Anyone can access it, anyone can overwrite it.

The standard safer way to do this is to wrap everything in a self-starting function:

 (function(){ // put some variables, flags, constants, whatever here. var myVar = "one"; // make your functions somewhere here var a = function(){ // Do some stuff here // You can access your variables here, and they are somehow "private" myVar = "two"; }; var b = function() { alert('hi'); }; // You can make b public by doing this return { publicB: b }; })(); 
+1
source

Source: https://habr.com/ru/post/947207/


All Articles