0

What is the different between following two methods of defining js function. I have seen this is some code some one given, but could not able to call the function inside of it.

1)

function sum () {
    var i, sum = 0;
    for (i = 0; i < arguments.length; i += 1) {
        sum += arguments[i];
    }
return sum;
};

2)

var sum = function () {
    var i, sum = 0;
    for (i = 0; i < arguments.length; i += 1) {
        sum += arguments[i];
    }
    return sum;
};
Gumbo
  • 643,351
  • 109
  • 780
  • 844

2 Answers2

1

The difference is that the var one is defined after the var is created, whereas the static one is defined without waiting for a var to get referenced.
You can call the "var one" only after you declare it since it is "known" at run-time.

example:

a(); // error - doesn't know a
var a = function(){alert('a')}

b(); // ok
function b(){ alert('b')}
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • So, can i access variables define in the var function? – Nisala Madhusanka May 24 '14 at 06:06
  • vars inside the function have their own scope. – Amir Popovich May 24 '14 at 06:07
  • 1
    They're both defined at runtime. Neither could possibly exist while the program is being parsed. – cookie monster May 24 '14 at 06:08
  • could you give me some sample tutorial links to study? – Nisala Madhusanka May 24 '14 at 06:11
  • @Nisala: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions, http://quirksmode.org/js/function.html, http://eloquentjavascript.net/chapter3.html – Felix Kling May 24 '14 at 06:12
  • @cookiemonster - I mean't that one is "known" in "real time" and therefore you can't invoke it before the var is declared. – Amir Popovich May 24 '14 at 06:14
  • @Amir: FWIW, the variable is also declared before the code is executed, but the assignment hasn't taken place yet. If the variable wasn't declared, you'd get a reference error. And this isn't specific to function expressions of course, every variable declarations work like this. – Felix Kling May 24 '14 at 06:24
  • @FelixKling - that's what I was trying to explain, but maybe I wasn't clear enough.. – Amir Popovich May 24 '14 at 06:29
  • Could you please explain me that how can i access "current" variable in this function. I cant paste all the code here (dont have space) `var PageTransitions = (function() { var $main = $( '#pt-main' ), animcursor = 1, pagesCount = $pages.length, current = 0; });` – Nisala Madhusanka May 24 '14 at 06:37
0

First can be used before declaring but second can be used only after its declaration..

halkujabra
  • 2,844
  • 3
  • 25
  • 35