5

In javascript, What is the difference between function declaration and function expression in terms of scope? function declaration means we are polluting the global space. Is it the same case with function expression?

Function declaration

function sum(){
 // logic goes here
}

Function expression

var sum = function(){}
casablanca
  • 69,683
  • 7
  • 133
  • 150
CKR
  • 213
  • 4
  • 8
  • http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname and http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascript – Phil Nov 10 '10 at 05:19

2 Answers2

10

Both are equivalent in terms of scope. A function declared inside another function will not be global. The difference is that you can use a declared function at any time (because it's hoisted before any code is run), a function assigned to a variable as an expression only after you have assigned it.

(function () {

    bar(); // works
    function bar() { }  // is not global

    foo();  // doesn't work
    var foo = function () { };

})();
deceze
  • 510,633
  • 85
  • 743
  • 889
5

As far as polluting the enclosing scope goes, both are equivalent. Note that it is not necessarily the global scope - it is the scope in which the function is declared (local functions are permitted within other functions). In your example, both methods introduce a variable (function object) named sum into the local scope.

casablanca
  • 69,683
  • 7
  • 133
  • 150