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; };
The:
is
function declarationwhich is hoisted to top by the interpreter, you can call from any place, while:is
function expressionyou can call only after it is defined. It won’t be available before or up in the code just like you were doing:Getting error because on first line
barisn’t available yet. To solve that, usefunction declarationinstead if you want.To learn more about the difference between
function declarationandfunction expression, I highly recommend you to read this great article by Kangax: