4 ms·
Actually, the reason you can use the function at a place in code before it's defined is actually because of variable hoisting. The name of the function is hoist
by arnorhs 13y ago
Actually, the reason you can use the function at a place in code before it's defined is actually because of variable hoisting. The name of the function is hoisted to the beginning of the scope in which it's defined. (this may be what you mean, but it was unclear from the comment)
But I agree that I don't think doing var func = function(){}; is in any way better than a normal function declaration. Actually, I think it's a bit ridiculous to even have one recommended over the other.
- rnd33 13y agoYes, a function definition is hoisted too but its implementation is always hoisted together with its declaration, preventing some bugs caused by variable hoisting. I made an example here: http://pastebin.com/2nS9EDPb http://pastebin.com/2nS9EDPb (Please correct me if I'm wrong, I wasn't aware for example that function declarations were treated as variables, redefinable etc)
- jbnicolai 13y agoNot just the name, the entire function declaration is hoisted. That's the difference between: function () { ... var a = function () {}; } which gets hoisted to: function () { var a; ... a = function () {}; } and: function () { ... function a () { }; } Which gets hoisted in it's entirety to: function () { function a () { }; ... } Which will cause difference behaviour between the two when calling a in the ... section, working in the latter case but undefined in the first. I don't think the grandparent was unclear about this in his post though.
- Zecc 13y agoAnd as a bonus, the latter gets its name set. Of course you could also name it in the function expression, but then you'd just be repeating yourself.
- jaredmcateer 13y agoThe main argument for a function expression assignment is that it behaves like everything else where as the function declaration does some magic. As long as you and all your team members are aware of said magic it's probably fine but personally I would side on consistency.