5 ms·
Pretty sure hoisting is totally unrelated to global variables. If a function is defined in a scope, it'll only be hoisted to the top of the scope.
by delluminatus 12y ago
Pretty sure hoisting is totally unrelated to global variables. If a function is defined in a scope, it'll only be hoisted to the top of the scope.
- couchand 12y agoAh, right. Should have left the original comment alone. Here's why you shouldn't rely on function hoisting: it gets weird. Weird enough that MDN has a section on it's "oddities" [0]. And since it doesn't add any expressive power, there's no compelling reason not to just treat all your code as data. [0]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheet#function_oddities https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- kevincennis 12y agoThat sounds like an argument for learning how hoisting works, not just avoiding it because it's "weird".
- warfangle 12y agoOr limiting when/where you define named functions it's pretty damn silly to declare a named function within an if block within a function call, especially if it has the same name as a function you've defined outside of it. I tend to limit them to "private" module functions. e.g., "use strict"; /*global module:true*/ function add(a, b) { return a+b; } module.exports = { sum : function(list) { return list.reduce(add, 0); } }; I don't declare named functions in a scope smaller than the module itself, so I don't really run into the 'weirdness' of hoisting. Then again, I've moved to commonjs style modules for everything - server side with node, client side with browserify (webpack does weird things with require()).
- couchand 12y agoI'd be in complete agreement if it offered any substantive benefits; however, I've yet to see an example of function-hoisting that can do something regular var-hoisting can't.
- woah 12y agoIt lets you put your functions where you want, for readability, but still be able to use them where they need to be used.
- couchand 12y agoSo does regular var-hoisting, which every JS developer already needs to know.