Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is the better way of defining a function? [duplicate]

Is there any difference between them ? I've been using both the ways but do not know which one does what and which is better?

function abc(){

    // Code comes here.
}

abc = function (){

    // Code comes here.
}

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

like image 546
Janak Avatar asked Jun 13 '13 11:06

Janak


1 Answers

function abc(){

    // Code comes here.
}

Will be hoisted.

abc = function (){

    // Code comes here.
}

Will not be hoisted.

For instance if you did:

 abc(); 
 function abc() { }

The code will run as abc is hoisted to the top of the enclosing scope.

If you however did:

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

abc is declared but has no value and therefore cannot be used.

As to which is better is more of a debate of programming style.

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

like image 111
Darren Avatar answered Sep 22 '22 11:09

Darren