4 ms·
This is referred to as "hoisting". As an aside, technically the latter's `var` declaration also gets destructured and hoisted as such... var foo; ... foo
by spmurrayzzz 12y ago
This is referred to as "hoisting". As an aside, technically the latter's `var` declaration also gets destructured and hoisted as such...
var foo;
...
foo = function() {
}
Also another difference in the latter is that its an anonymous function, which is commonly seen in assignment expressions — but you could also name it for more informative logging.
var foo = function realName(){};
- akbar501 12y agoOne gotcha about naming otherwise anonymous functions is that the function name is often removed during minification. So, if you have code or logging that assumes all functions have names, then the code may break or degrade when built and deployed in production.
- gorhill 12y ago> more informative logging. > var foo = function realName(){}; Nice trick, thanks! The "anonymous" function is especially annoying when profiling code, so that should address that annoyance. I often struggle with picking names, but another post here shows that "foo" can just be reused as the function name.
- XaspR8d 12y ago> I often struggle with picking names, but another post here shows that "foo" can just be reused as the function name. I'd be very careful about giving them the same name if you're working with IE at all. IE8 and below's JScript does some really strange stuff with function expressions, leaking and hoisting them all over the place. [1] Instead, I'd just append a character or something to differentiate the two. I've been using the format advocated for in Javascript Patterns[2][3]: var foo = function fooF(){}; [1] http://kangax.github.io/nfe/#jscript-bugs http://kangax.github.io/nfe/#jscript-bugs [2] http://shichuan.github.io/javascript-patterns/ http://shichuan.github.io/javascript-patterns/ [3] https://github.com/shichuan/javascript-patterns/blob/master/general-patterns/function-declarations.html https://github.com/shichuan/javascript-patterns/blob/master/...
- gorhill 12y agoThanks for the tip, adopted. The kind of tip that might have saved me a lot of time in the future.
- pyre 12y agoNaming the anonymous functions, is actually suggested as good practice somewhere in the Angular.js docs. I came across that a couple of weeks ago.
- whiskypeters 12y agoNaming anonymous functions (and anonymous function expressions) provides useful context while tracing error stacks
- pyre 12y agoThis was exactly the reason it was suggested in the Angular.js docs.