Not 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.
And 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.
Yes, 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
(Please correct me if I'm wrong, I wasn't aware for example that function declarations were treated as variables, redefinable etc)
Re:Javascript patterns
by jaredmcateer on Thursday January 02, 2014 @09:52AM
(#6999783)
The 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.
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.