user1448287
user1448287

Reputation: 13

what is the difference between the below syntaxes?

1. $(function () {
       function foo() { return true; }
       log(bar());                        // getting error
       var bar = function() { return true; };   
  });

2. $(function () {
       function foo() { return true; }
       var bar = function() { return true; };
       log(bar());                        // Working   
  });

my confusion here is what is the difference between the below two declarations and which one is useful?

var bar = function() { return true; };

function bar(){ return true; };

Upvotes: 1

Views: 71

Answers (2)

Sarfraz
Sarfraz

Reputation: 382919

The:

function bar(){ return true; };

is function declaration which is hoisted to top by the interpreter, you can call from any place, while:

var bar = function() { return true; };

is function expression you can call only after it is defined. It won't be available before or up in the code just like you were doing:

log(bar());                        // getting error
var bar = function() { return true; }; 

Getting error because on first line bar isn't available yet. To solve that, use function declaration instead if you want.


To learn more about the difference between function declaration and function expression, I highly recommend you to read this great article by Kangax:

Upvotes: 4

Someth Victory
Someth Victory

Reputation: 4559

Sarfraz got a great explanation already. I just want to add more, the first function,

var bar = function(){ return true; };

is much more flexible, you can add some more properties, or methods after it is declared:

bar.anotherMethod = function() { alert("This is another method"); }
bar.anotherProperty = 'some value';

While function bar(){ return true; } cannot do it that way. `

Upvotes: 0

Related Questions