0

I was going through this code :

https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json_parse.js

All functions in this file are defined as

var foo = function() {}

instead of

function foo(){}

I am quiet aware of what each style represents and how to use them. However I am yet to see a convincing answer on what the advantage of using the first pattern over the second one is.

Is it just because.. "functions are first class objects .. they can be assigned and tossed around.. so why not??"

or is there some solid reason behind this ?

runtimeZero
  • 26,466
  • 27
  • 73
  • 126
  • http://www.dustindiaz.com/javascript-function-declaration-ambiguity/ – Shimon Brandsdorfer Nov 11 '15 at 15:09
  • it's just a codestyle – vp_arth Nov 11 '15 at 15:11
  • 3
    @vp_arth Definitely **NOT** "just a codestyle", they are different (function hoisting). – Shomz Nov 11 '15 at 15:13
  • There could be different advantages depending on what you're trying to achieve. Using the first example, allows you to declare an empty variable first and only assign the function later in the code and even change its value in different states of your program. It also means you can't call the function/variable before it has been declared. The latter, for example, allows you to call a function before it has been declared. I really advise you to read this http://www.w3schools.com/js/js_function_definition.asp – Miguel M. Nov 11 '15 at 15:13
  • different, but still `just a codestyle`. I prefer `regular declaration`, because I can lift all my function implemetations down in my code. – vp_arth Nov 11 '15 at 15:15
  • 1
    yes.. this seems like a duplicate.. we can close this question. – runtimeZero Nov 11 '15 at 15:23
  • After staring at the code for multiple hours I kindof got the idea why the author used this pattern of function definition.. apparently I am guessing that the author is relaying a sense of flow in the program. Changing the order of the function declaration actually breaks the program. So it seems the author is relaying that these functions have to be declared before this .. – runtimeZero Nov 12 '15 at 14:28

0 Answers0